Using math.isclose() to Compare Floats in Python
Comparing floating-point numbers in Python using the standard
equality operator (==) frequently leads to unexpected bugs
due to hardware-level binary representation errors. The purpose of
Python's math.isclose() function is to safely compare two
floating-point numbers by checking if they are "close" to each other
within an acceptable margin of error. This article explains why
floating-point inaccuracies happen, how math.isclose()
works, and how to use it effectively in your code.
The Problem with Direct Float Comparison
Computers represent floating-point numbers in base-2 (binary) according to the IEEE 754 standard. Because certain base-10 fractions (like 0.1 or 0.2) cannot be represented cleanly in finite binary digits, small rounding inaccuracies occur.
For example:
print(0.1 + 0.2 == 0.3) # Outputs: False
print(0.1 + 0.2) # Outputs: 0.30000000000000004Because 0.1 + 0.2 evaluates to slightly more than
0.3, testing equality with == returns
False.
The Solution:
math.isclose()
Introduced in Python 3.5, math.isclose() determines
whether two values are considered equal by verifying if the difference
between them falls within a specified tolerance threshold.
The function signature is:
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)The parameters function as follows:
aandb: The two numeric values being compared.rel_tol(Relative Tolerance): The maximum allowed difference relative to the larger absolute value ofaorb. The default value is1e-09, meaning the values must match within 9 decimal places. This is ideal for most general comparisons where numbers vary in scale.abs_tol(Absolute Tolerance): A fixed maximum difference regardless of the magnitude of the numbers. The default is0.0. This parameter is necessary when comparing values that are very close to zero.
Practical Example
Here is how math.isclose() resolves standard
floating-point equality errors:
import math
a = 0.1 + 0.2
b = 0.3
# Standard equality fails
print(a == b) # False
# math.isclose succeeds
print(math.isclose(a, b)) # TrueWhen to Use abs_tol
When comparing numbers near zero, relative tolerance alone is often
insufficient. For instance, comparing 1e-10 to
0.0 will fail with the default rel_tol because
the relative difference relative to the larger number is 100%. In such
cases, define abs_tol:
import math
# Fails with default parameters
print(math.isclose(1e-10, 0.0)) # False
# Succeeds with an explicit absolute tolerance
print(math.isclose(1e-10, 0.0, abs_tol=1e-9)) # TrueConclusion
Direct equality (==) should almost never be used with
floating-point calculations in Python. By using
math.isclose(), you account for underlying binary precision
limitations, ensuring your conditional checks and tests behave reliably
and as expected.