Because floating-point arithmetic accumulates tiny rounding errors, comparing computed float arrays with == can incorrectly report 'not equal' even when two arrays represent the same mathematical result. allclose() instead checks whether each pair of elements differs by less than a combined tolerance of atol plus rtol times the absolute value of the second element, returning a single overall True only if every element pair passes that check. It's the standard way to compare floating-point array results in tests and numerical code, rather than exact equality.
1Understanding np.allclose()
Because floating-point arithmetic accumulates tiny rounding errors, comparing computed float arrays with == can incorrectly report 'not equal' even when two arrays represent the same mathematical result. allclose() instead checks whether each pair of elements differs by less than a combined tolerance of atol plus rtol times the absolute value of the second element, returning a single overall True only if every element pair passes that check. It's the standard way to compare floating-point array results in tests and numerical code, rather than exact equality.
Never use == to compare two arrays of computed floating-point results — always use np.allclose(), or np.isclose() for element-wise detail, with an appropriate tolerance instead, since floating-point rounding error makes exact equality unreliable.
import numpy as np
a = np.array([0.1 + 0.2, 1.0])
b = np.array([0.3, 1.0])
print(a == b)
print(np.allclose(a, b))2Practical Example
Here is a real-world application of np.allclose() showing how it is used in production NumPy code.
import numpy as np
result = np.array([1.0000001, 2.0])
expected = np.array([1.0, 2.0])
print(np.allclose(result, expected, atol=1e-5))3Best Practices
Follow these guidelines when working with np.allclose():
1. Use np.allclose() instead of == whenever comparing arrays of computed floating-point values, in tests or elsewhere
2. Adjust rtol/atol thoughtfully based on the expected magnitude and precision of your specific calculation, rather than always relying on the defaults
3. Use np.isclose() instead when you need the per-element boolean detail rather than a single overall True/False
Tip: Never use == to compare two arrays of computed floating-point results — always use np.allclose(), or np.isclose() for element-wise detail, with an appropriate tolerance instead, since floating-point rounding error makes exact equality unreliable.
import numpy as np
a = np.array([0.1 + 0.2, 1.0])
b = np.array([0.3, 1.0])
print(a == b)
print(np.allclose(a, b))