How do fortran conditional statements handle float

2019-08-29 02:40发布

I have a simple if conditional statement that is comparing two real numbers (one is read from an array that is allocated and initialized in an imported module) that is failing when it shouldn't.

Under what circumstances might this happen?

I'm using the Intel compiler.

Edit: For further clarification, I am doing something like this:

if (12.2272 >= -5.0000) then
  do something
else
  print *, 'fail'
endif

I'm getting fail. The same goes for when I evaluate with only > rather than >=.

标签: fortran
1条回答
乱世女痞
2楼-- · 2019-08-29 02:59

Usually, you can compare floating point numbers reliably only with some tolerance, because of their inherent non-preciseness. Generally, you shouldn't compare for equality at all except some special cases, like comparing a directly read value with some small integer, typically 0.

If you did any non-trivial computing with one of the numbers, don't compare for equality at all. With some tolerance, you can use:

if (abs(a-b)<eps) ...

where eps is some small number. It can be some (even large) multiple of the epsilon intrinsic function result.

It's good to read some article about floating points, like http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

You can try this little program to see the typical problem with floating point numbers

real x
integer i

x = 0
do i = 1,10
   x = x + 0.1
end do

print *, x, x==1

end
查看更多
登录 后发表回答