About Floating-point Number Equalities

Floating point operations are inaccurate because of the nature of computer architecture. Instead of equality, check proximity:

1
2
3
4
>>> def isclose(a, b, rtol=1e-09, atol=0.0):
...    return abs(a-b) <= max(rtol * max(abs(a), abs(b)), atol)

>>> isclose(1, 0.999999999) == True

Here

  • rtol is relative tolerance.
  • atol is absolute tolerance.
  • abs(x) returns absolute value |x| (x without a negative sign).
  • max(*args) returns the largest argument.

To clarify the notation used in the function:

1
2
1e-09 == 0.0000000001
1e+09 == 1000000000.0

Tips and Tricks Programming Python 3