Compare Floating-Point Values with isclose
Core idea
Binary float cannot represent many decimal fractions exactly. math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0) accepts differences up to the larger of the absolute tolerance and the relative tolerance times max(abs(a), abs(b)). Choose tolerances from the measurement requirements, not arbitrarily.
import mathprint(0.1 + 0.2 == 0.3)print(math.isclose(0.1 + 0.2, 0.3))Approximate equality succeeds despite representation error.
Compare against zero
import mathprint(math.isclose(0.0002, 0))print(math.isclose(0.0002, 0, abs_tol=0.001))A meaningful absolute tolerance is needed near zero.
Accumulate small contributions
import mathprint(math.fsum([1e16, 1, -1e16]))print(math.isfinite(float("inf")))fsum tracks intermediate sums to improve accuracy; isfinite rejects infinity and NaN.
Common mistake
isclose is not exact equality or a replacement for validation. NaN is never close, even to itself; infinity is close only to itself.
Practice
Compare readings with target zero and an absolute tolerance of 0.01; try positive and negative readings.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Floating-point tolerances
Check your understanding of isclose and floating error.
What is printed?
import mathprint(math.isclose(0.3, 0.1+0.2))What is printed?
import mathprint(math.isclose(0, -0.002), math.isclose(0, -0.002, abs_tol=0.003))What is printed?
import mathprint(math.isclose(math.nan, math.nan), math.isclose(math.inf, math.inf))How should tolerances be selected?