How math.isclose Works in Python: Tolerances Explained

Due to the way computers store floating-point numbers in binary format, direct equality checks (a == b) often fail due to rounding errors. Python's math.isclose() function resolves this by evaluating whether two values are close enough to be considered equal based on specified tolerance thresholds. This article breaks down the mathematical formula used by math.isclose() and details how it applies relative tolerance (rel_tol) and absolute tolerance (abs_tol) to make this determination.

The Underlying Evaluation Formula

The math.isclose() function determines equivalence by checking if the absolute difference between two numbers is less than or equal to the greater of two tolerance thresholds. The exact mathematical criterion evaluated is:

abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

If the condition evaluates to True, the function returns True; otherwise, it returns False.

Relative Tolerance (rel_tol)

Relative tolerance measures the allowable difference relative to the magnitude of the values being compared.

Absolute Tolerance (abs_tol)

Absolute tolerance is a fixed, unchanging minimum threshold for the allowable difference between two numbers.

How the Criteria Interact

By using the max() function between the relative and absolute thresholds, math.isclose() ensures that:

  1. For large numbers: The relative tolerance term (rel_tol * max(abs(a), abs(b))) is typically larger than abs_tol, meaning the function automatically scales the acceptable margin of error to the size of the inputs.
  2. For numbers near zero: The relative term shrinks toward zero. If defined, abs_tol takes precedence as the larger value, preventing comparisons against zero from failing due to minor floating-point imprecision.

Special Values and Constraints