Numpy allclose() function with examples

In this tutorial, we will learn how to use Numpy’s allclose() function to compare two Numpy arrays. Numpy’s allclose() function compares two arrays element-wise for similarity and tell us if all the elements close enough as defined tolerance specified by user. It returns True if all the elements are close between two arrays and False even if one of the elements is not close enough.

Here is the basic syntax of Numpy’s allclose() function.

numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

Numpy’s allclose() can take five arguments. The first two arguments are array-like, the input arrays that we want to compare. It can take rtol – relative tolerance and atol– absolute tolerance to decide if two elements in two arrays are close.

These two tolerance values are positive and very small numbers. The allclose() function uses the relative difference (rtol), absolute difference(atol) using thee formula given below to compare against the absolute difference between a and b.

absolute(a - b) <= (atol + rtol * absolute(b))

And it returns True if the above equation is element-wise True. then allclose returns True.

Here is an example of using allclose() to compare two arrays:

import numpy as np

Leet us define two arrays with three elements each. The first two elements of both the arrays are the same. The third element is different by a small amount.

# Create two arrays to compare
a = np.array([1.0, 2.0, 3.0])
b = np.array([1.0, 2.0, 3.001])

When we compare these two arrays with rtol=0.01, we get the results as TRUE. The absolute difference is smaller than the tolerance value computed by the above formula as default atol is very small 1e-8 .

np.allclose(a, b, rtol=0.01)

True

We get the same answer that the two arrays are close when use atol=0.001 as well.

np.allclose(a, b, atol=0.01)

True

For the same two arrays, but with a relative tolerance value rtol=0.0001, we get the answer False, i.e. the two arrays are not close.

np.allclose(a, b, rtol=0.0001)

Falsee

Numpy allcose() vs Numpy isclose()

Another function that is similar to allclose() is Numpy’s isclose() function.

Numpy’s allclose() is similar to isclose() function in the sense that they both try to find if two arrays are close by making element-wise comparison.

However the big difference between Numpy’s isclose() and allclose() function is that Numpy’s isclose() return a boolean vector with TRUE/FALSE values for element-wise comparison. For example, if we are comparing two arrays of length N, we will get a boolean vector of length N, with True for elements that are close and False otherwise. However, Numpy’s allclose() returns a single boolean/logical value using element-wise comparison.

1 comment

Comments are closed.