Community
cancel
Showing results for 
Search instead for 
Did you mean: 
avinashs
New Contributor I
79 Views

Comparison of two real numbers for equality

Jump to solution

One of the first things I was taught in my Fortran course some 30+ years ago was that testing two real variables (single or double precision) for equality was not reliable and that round-off errors may give a false result. On the other hand, comparing two integers is always accurate. Does this rule still hold true for real variables? In particular, will the following code always produce the correct result. I am willing to accept numbers that differ by less than epsilon(1.0d0) to be considered equal.

program main
real(kind = :: a(10), b(10)
a = 1.0d0
b = 1.0d0
if (all(a == b)) then
print *, 'arrays are have equal values'
else
print *, 'arrays are different'
end if
read *
end program main

0 Kudos

Accepted Solutions
JohnNichols
Valued Contributor I
67 Views

You should always set a delta for the numbers and accept if abs(a-b) < delta then equal -- otherwise not really reliable 

View solution in original post

1 Reply
JohnNichols
Valued Contributor I
68 Views

You should always set a delta for the numbers and accept if abs(a-b) < delta then equal -- otherwise not really reliable 

View solution in original post