Avoiding Exact Floating-point Comparison

It is unsafe for applications to rely on exact floating-point comparisons. Slight variations in rounding can change the outcome of such comparisons, leading to non-convergence or other unexpected behavior.

Tests for equality of floating-point quantities should be made within some tolerance related to the expected precision of the calculation, for example, by using the Fortran intrinsic function EPSILON. The following examples demonstrate the concept:

Example

if (foo() == 2.0)

Where foo() may be as close to 2.0 as can be imagined without actually exactly matching 2.0. You can improve the behavior of such codes by using inexact floating-point comparisons or fuzzy comparisons to test a value to within a certain tolerance, as shown below:

Example

epsilon = 1E-8;
if (abs(foo() - 2.0) <= epsilon)