mikemike
mikemike

Reputation: 157

Fortran 95: inline evaluation of if-conditions

Here a small snippet of code that returns epsilon() for a real value:

program epstest
real :: eps=1.0, d
do
  d=1.0+eps  
  if (d==1.0) then
    eps=eps*2
    exit
  else
    eps=eps/2
  end if
end do
write(*,*) eps, epsilon(d)
pause
end program

Now, when I replace the if condition by

   if (1.0+eps==1.0) then

the program should have the same in return but it unfortunately does not! I tested it with the latest (snapshot) release of g95 on Linux and Windows.

Can someone explain that issue to me?

Upvotes: 1

Views: 1357

Answers (1)

M. S. B.
M. S. B.

Reputation: 29391

Floating point arithmetic has many subtle issues. One form of source code can generate different machine instructions than another seemingly almost identical source code. For example, "d" might get stored to a memory location, while "1.0 + eps" might be evaluated solely with registers ... this can cause different precision.

More generally, why not use the intrinsic functions provided for Fortran 95 that disclose the characteristics of a particular precision of reals?

Upvotes: 3

Related Questions