CKTIS / Python
math.isclose
Tests numerical proximity using relative and absolute tolerances.
Version: Python 3.14; repository image, production runtime not attested
Syntax
math.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0)Tests numerical proximity using relative and absolute tolerances.
A positive absolute tolerance is needed to regard a small nonzero number as close to zero under ordinary relative tolerances.
For finite inputs the permitted absolute difference is the larger of the absolute tolerance and the relative tolerance multiplied by the larger magnitude. The binary rounding mismatch in 0.1 + 0.2 passes the default relative test. Against zero the supplied absolute tolerance accepts 1e−12. Infinities are close only to the same signed infinity. NaN is never close, including to itself.
import math
assert math.isclose(math.inf, math.inf) and not math.isclose(math.inf, -math.inf)
assert not math.isclose(math.nan, math.nan)
a, b = 0.1 + 0.2, 0.3
assert abs(a-b) <= max(1e-9 * max(abs(a), abs(b)), 0.0)
assert not math.isclose(0, 1e-12) and math.isclose(0, 1e-12, abs_tol=1e-10)
Examples
import math
print(math.isclose(0.1 + 0.2, 0.3))
print(math.isclose(0, 1e-12, abs_tol=1e-10))
Result
True True
For finite inputs the permitted absolute difference is the larger of the absolute tolerance and the relative tolerance multiplied by the larger magnitude. The binary rounding mismatch in 0.1 + 0.2 passes the default relative test. Against zero the supplied absolute tolerance accepts 1e−12. Infinities are close only to the same signed infinity. NaN is never close, including to itself.