How to Check If a Number Is Close to Another in Python
When working with floating-point numbers in Python, testing for equality using == is often unreliable. Due to how computers represent decimal numbers in binary (IEEE 754 standard), simple arithmetic like 0.1 + 0.2 does not exactly equal 0.3.
This guide explains why direct comparisons fail and how to use math.isclose() and absolute difference calculations to correctly determine if two numbers are "close enough" to be considered equal.
The Problem: Floating-Point Inaccuracy
Computers store numbers in binary. Some decimal fractions (like 0.1) cannot be represented exactly in binary, leading to tiny precision errors that accumulate during calculations.
# The classic floating-point arithmetic issue
num1 = 0.1 + 0.2
num2 = 0.3
print(f"num1: {num1:.17f}")
print(f"num2: {num2:.17f}")
# ⛔️ Incorrect: Direct equality check fails
if num1 == num2:
print("Equal")
else:
print("Not Equal")
Output:
num1: 0.30000000000000004
num2: 0.29999999999999999
Not Equal
Method 1: Using math.isclose (Recommended)
Introduced in Python 3.5, the math.isclose() function is the robust, standard way to compare floating-point numbers. It checks if two values are within a relative or absolute tolerance of each other.
import math
val_a = 0.1 + 0.2
val_b = 0.3
# ✅ Correct: returns True if values are close
if math.isclose(val_a, val_b):
print(f"{val_a} is close to {val_b}")
else:
print("Values differ significantly.")
Output:
0.30000000000000004 is close to 0.3
Customizing Tolerance
You can adjust strictness using rel_tol (relative tolerance) and abs_tol (absolute tolerance).
import math
a = 10.0
b = 10.05
# Check with default tolerance (usually 1e-09)
print(f"Default check: {math.isclose(a, b)}")
# ✅ Relaxing the tolerance (allowing ~5% difference)
print(f"Relaxed check: {math.isclose(a, b, rel_tol=0.05)}")
Output:
Default check: False
Relaxed check: True
Relative tolerance (rel_tol) handles large numbers well (e.g., is 1,000,000 close to 1,000,001?). Absolute tolerance (abs_tol) is useful for numbers close to zero, where relative differences can be misleading.
Method 2: Calculating Absolute Difference
If you are using an older version of Python or need a simple, specific threshold logic without importing modules, you can calculate the absolute difference.
The logic is: |a - b| <= tolerance.
val_a = 0.1 + 0.2
val_b = 0.3
tolerance = 1e-9 # 0.000000001
# ✅ Manual check using abs()
difference = abs(val_a - val_b)
if difference <= tolerance:
print("Approximately Equal")
else:
print("Not Equal")
Output:
Approximately Equal
Using a fixed tolerance (e.g., 1e-9) works well for small numbers like 1.0 or 0.5, but may fail for very large numbers where floating-point spacing is larger than your tolerance. math.isclose handles this scaling automatically.
Method 3: Checking Arrays with NumPy
If you are working with data science libraries, you likely have arrays of numbers rather than scalars. Standard Python functions won't work on arrays directly. Use numpy.isclose().
import numpy as np
# Arrays of floats
data_calculated = np.array([0.1 + 0.2, 1.0 / 3.0])
data_expected = np.array([0.3, 0.3333333333333333])
# ✅ Check element-wise closeness
matches = np.isclose(data_calculated, data_expected)
print(f"Matches: {matches}")
print(f"All close? {np.all(matches)}")
Output:
Matches: [ True True]
All close? True
Conclusion
To check if numbers are close in Python:
- Use
math.isclose(a, b)for standard scalar comparisons. It is robust, explicit, and handles tolerances automatically. - Use
abs(a - b) <= tolonly if you need a quick, manual implementation without imports. - Use
numpy.isclose(arr1, arr2)when working with lists or arrays of data. - Avoid
==for floats, as it requires bit-for-bit equality which is rarely achieved in computed values.