Use math.isclose for a tolerance-based measurement check
Also published in our Blogger archive.
A sensor reading rarely arrives as the exact decimal value written in a specification. Comparing two floating-point measurements with == therefore makes a brittle acceptance rule. math.isclose() expresses the rule directly: two values are close when their difference fits either the relative tolerance or the absolute tolerance. It has been available since Python 3.5.
This example checks a 12.000 mm target. A 12.004 mm reading passes because it is within the chosen 0.005 mm absolute tolerance, while 12.007 mm fails. The assertions document both expected decisions before the program prints them. An absolute tolerance is especially important when a value may be near zero: relative tolerance alone cannot make a nonzero value close to 0.0 under the usual settings.
Choose tolerance from the instrument, process requirement, and units; it is a domain decision, not a property inferred by isclose(). The example does not establish calibration, measurement uncertainty, or suitability for safety-critical acceptance. It only verifies the stated numeric rule for these two inputs. NaN is not close to anything, and infinities are close only to themselves, so callers handling such values should decide how to report them.
See the official math.isclose documentation for its tolerance formula and special-value behavior.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed against the requirements of its intended application.
import math
target_mm = 12.000
absolute_tolerance_mm = 0.005
within_tolerance = math.isclose(
12.004, target_mm, rel_tol=0.0, abs_tol=absolute_tolerance_mm
)
outside_tolerance = math.isclose(
12.007, target_mm, rel_tol=0.0, abs_tol=absolute_tolerance_mm
)
assert within_tolerance is True
assert outside_tolerance is False
print(f"12.004 mm accepted: {within_tolerance}")
print(f"12.007 mm accepted: {outside_tolerance}")
12.004 mm accepted: True
12.007 mm accepted: False