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 >=
.
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:
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