math.isclose
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)Test whether two floats are close enough under a relative or absolute tolerance. This is a numeric comparison, not an exact equality test.
| Parameter | Description |
|---|---|
a, b | The values to compare, typically floats. |
rel_tol | Maximum allowed difference relative to the larger magnitude of a and b. The default is 1e-09. |
abs_tol | Maximum allowed difference regardless of magnitude. The default is 0.0. |
Returns: True if the values are considered close, otherwise False.
- 0.1 + 0.2 == 0.3 is False, but math.isclose(0.1 + 0.2, 0.3) is True with the default relative tolerance.
- math.isclose(1e-200, 0.0) is False until you pass a suitable abs_tol, because the default absolute tolerance is 0.0.
- rel_tol=0.001 treats 1000 and 1001 as close, but not 1000 and 1002, because the allowed difference is 0.001 * 1002.
import math
print(0.1 + 0.2 == 0.3, 0.1 + 0.2)
print(math.isclose(0.1 + 0.2, 0.3))
print(math.isclose(1e-200, 0.0), math.isclose(1e-200, 0.0, abs_tol=1e-150))
print(math.isclose(float("nan"), float("nan")))
print(math.isclose(float("inf"), float("inf")))
print(math.isclose(1000, 1001, rel_tol=0.001), math.isclose(1000, 1002, rel_tol=0.001))Expected output
False 0.30000000000000004
True
False True
False
True
True False