Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
Announcements
The Intel sign-in experience has changed to support enhanced security controls. If you sign in, click here for more information.
27778 Discussions

Comparison of two real numbers for equality

avinashs
New Contributor I
785 Views

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
1 Solution
JohnNichols
Valued Contributor II
772 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 II
773 Views

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

Reply