-1

Why do I get different results using "DMOD" in Fortran and "numpy.remainder" in Python?

In Fortran:

DOUBLE PRECISION aaa,bbb
aaa = 2.11561
bbb = 1.19841
out = DMOD(aaa, bbb)
print*,out

and I get: 0.917199850

In python:

import numpy as np
print(np.remainder(2.11561,1.19841))

and I get: 0.9172000000000002

francescalus
  • 30,576
  • 16
  • 61
  • 96
scana
  • 111
  • 1
  • 11
  • 4
    Your Fortran constants are single-precision. Double precision constants have a different syntax, e.g. `1.2D9` (the `D` indicates double precision). – Tom Karzes Aug 06 '20 at 21:44
  • 2
    Not also dmod is archaic since the new-fangled overloading of intrinsic functions that came into the language in 1977. Simply use Mod( aaa, bbb ) – Ian Bush Aug 06 '20 at 21:53
  • Thanks. My example is with DMOD because I'm converting a Fortran 77 code to python. If I use D (aaa = 2.11561D0) I get 0.917200029 that is closer but not perfect – scana Aug 06 '20 at 22:12
  • 3
    You have to add `out` to the list of variables that are declared to be `double precision`: `DOUBLE PRECISION aaa,bbb,out` – Warren Weckesser Aug 06 '20 at 22:41
  • 3
    Your variable `out` is implicitly `real`, which causes the result to be converted to single-precision. To retain the full double-precision result, you need to declare `out` to be `double`. That may account for the remaining difference. – Tom Karzes Aug 06 '20 at 22:44
  • 1
    @scana MOD was preferable to DMOD already in Fortran 77. – Vladimir F Героям слава Aug 07 '20 at 07:00
  • Thanks Warren and Tom, that (out as double precision) solved the problem. I'm converting this old code and there are a lot of missed declarations that definitively need to be checked. – scana Aug 07 '20 at 07:08
  • 2
    IMPLICIT NONE is your friend ... always! – Ian Bush Aug 07 '20 at 11:25

1 Answers1

2

If you want double-precision in Fortran, you need to write the constants that way too. You might do it this way, by using a _dp suffix:

integer, parameter:: dp=kind(0.d0)
aaa = 2.11561_dp

Or you might use the d in the number:

aaa = 2.11561d0

You use e for single precision and d for double precision. Single precision is default... and even if the variable is double-precision, the constant might be single-precision! It is the same way in C.

The difference is that Python and C use double-precision by default, and you have to ask for single precision.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415