Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 367
Below the Radar Avatar asked May 18 '26 05:05

Below the Radar


1 Answers

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
like image 110
unutbu Avatar answered May 19 '26 18:05

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!