numpy.allclose() compare arrays with floating points

I have two numpy arrays:

g1 = np.array([3118740.3553, 3520175.8121]) g2 = np.array([3118740.8553, 3520176.3121]) 

I want to use numpy.allclose() to test if those arrays are identical inside the floating point precision tolerance

np.allclose(g1, g2, atol=1e-7) 

Curiously it returns True even if the difference between those two arrays is significant. Why?

1 Answer

The call signature of np.allclose is

In [4]: np.allclose? Signature: np.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False) 

Notice that the default for rtol (relative tolerance) is 1e-05. As long as

abs(a[i] - b[i]) <= rtol * abs(b[i]) + atol 

for all i = 0, ..., len(a), then np.allclose returns True.

In [11]: rtol, atol = 1e-05, 1e-7 In [12]: [abs(ai - bi) < rtol * abs(bi) + atol for ai, bi in zip(g1, g2)] Out[12]: [True, True] 

Since the values in g2 are large, even a small rtol leads to a fairly large tolerance:

In [14]: rtol * g2.min() Out[14]: 31.187408553 

If you don't want to include a relative tolerance, you must set it to zero to override the default:

In [13]: np.allclose(g1, g2, rtol=0, atol=1e-7) Out[13]: False 
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like