numpy.allclose() in Python
Last Updated :
09 Dec, 2025
numpy.allclose() is a NumPy function used to check whether two arrays are approximately equal element-wise within a given tolerance. It is useful when comparing floating-point numbers, where tiny differences may occur due to precision issues.
The function returns True only if every element of the first array is close to the corresponding element in the second array, based on the formula:
abs(arr1 - arr2) <= atol + rtol * abs(arr2)
If the arrays contain NaN, the function returns False unless the argument equal_nan=True is used.
Example: This example checks if two arrays are almost equal by allowing small numerical differences. We set custom tolerance values and compare both arrays.
Python
import numpy as np
a1 = np.array([5e5, 1e-7, 4.000004e6])
a2 = np.array([5.00001e5, 1e-7, 4e6])
res = np.allclose(a1, a2, rtol=1e-05, atol=1e-08)
print(res)
Explanation:
- np.allclose(a1, a2, rtol=1e-05, atol=1e-08) compares elements using absolute and relative tolerance.
- Returns True because differences are within allowed tolerance.
Syntax
numpy.allclose(arr1, arr2, rtol=1e-05, atol=1e-08, equal_nan=False)
Parameters:
- arr1, arr2: Input arrays to compare
- rtol: Relative tolerance (allowed proportional difference)
- atol: Absolute tolerance (minimum allowed difference)
- equal_nan: Treat NaN values as equal if True
Examples
Example 1: This example compares two arrays using the default behavior. The values differ slightly but remain within tolerance.
Python
import numpy as np
a1 = np.array([1000.0, 2.5, 3.0001])
a2 = np.array([1000.00001, 2.5, 3.0000])
res = np.allclose(a1, a2)
print(res)
Explanation:
- np.allclose(a1, a2) uses default rtol and atol.
- Minor floating-point differences are acceptable returns True.
Example 2: Here we use smaller tolerance values, making the comparison stricter. The same arrays now fail the closeness test.
Python
import numpy as np
a1 = np.array([10.0, 20.0005])
a2 = np.array([10.0, 20.0])
res = np.allclose(a1, a2, rtol=1e-07, atol=1e-09)
print(res)
Explanation:
- rtol=1e-07 & atol=1e-09 very strict tolerance.
- Difference in 20.0005 is larger function returns False.
Example 3: By default, NaN values are not considered equal. Setting equal_nan=True allows comparing arrays containing NaN.
Python
import numpy as np
a1 = np.array([1.0, np.nan, 5.0])
a2 = np.array([1.0, np.nan, 5.0])
res = np.allclose(a1, a2, equal_nan=True)
print(res)
Explanation:
- equal_nan=True treats corresponding NaN elements as equal.
- All elements match returns True.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice