14.4 Comparing floating-point numbers

Because floating-point representations are inexact, it is rarely a good idea to test exact inequality. The general recommendation is that rather than testing x == y, an approximate test may be used given an absolute or relative tolerance.

Given a positive absolute tolerance of epsilon, x can be compared to y using the conditional

abs(x - y) <= epsilon.

Absolute tolerances work when the scale of x and y and the relevant comparison is known.

Given a positive relative tolerance of epsilon, a typical comparison is

2 * abs(x - y) / (abs(x) + abs(y)) <= epsilon.