Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

mod intrinsic function with real(8)

fritschen
Beginner
434 Views
The following small program gives an output that is not clear to me:

real(8) :: d1,d2

d1 = 12d0
d2 = 1d-3

write(*,*) mod(d1,d2), d1 - int(d1/d2)*d2
end

The output is:

9.999999999997502E-004 0.000000000000000E+000

According to the compiler documentation, mod(d1,d2) should be the same as d1 - int(d1/d2)*d2.
I'm using Visual Fortran Compiler XE, Version 12.1.0.233

Has anybody an idea what is going on here?
Thanks
Ralf
0 Kudos
3 Replies
tom_p
Beginner
434 Views
It seems as if the mod function suffers from some kind of floating point rounding error. You would get this result if 12. / 1.e-3 would be rounded down to 11999, which I believe is incorrect if you strictly adhere to the standard. Unfortunately the problem did not go away when compiling with /fp:strict.

However, it probably is a good idea to design a program in a way that makes it unsusceptible to these kinds of floating point errors. (Admittedly that is rarely easy to do.)
0 Kudos
dannycat
New Contributor I
434 Views
Regarding the mod intrinsic function: I recently encountered strange behaviour when I accidently tried to use the mod function with a zero for the second argument. Instead on terminating the program with an erroror returning a zero value the program jumped to a different part (when debugging). It purely by chance that I found the cause. Should the program not terminate when statements like:

j = 0
j1 = mod(i,j)

are encountered?
0 Kudos
Steven_L_Intel1
Employee
434 Views
I can reproduce this. With optimization, the operations are done at compile time, but the results are the same with /Od. My guess is that it's the "formula" that is not giving the best result, considering that the second argument is not exactly representable and that the MOD is giving an answer closer to the infinite precision result. I will poke at this some more.
0 Kudos
Reply