NumPy allclose() Method Illustration – With Examples

Hello coders!! This article will be learning about the NumPy.allclose() method in Python. NumPy is an inbuilt module in Python used for array-like functions. Without much further ado, let us dive straight into the topic.

What is NumPy allclose()?

numpy.allclose() is a function of the NumPy module in Python. It is used to find if two arrays are equal element-wise within a given tolerance. The tolerance values are small positive numbers.

The relative and absolute differences are added together and compared against the absolute difference between two arrays. If either array contains one or more NaNs, it returns False. Items are treated as equal if they are in the same place and of the same sign in both arrays.

Syntax:

numpy.allclose(arr1, arr2, rtol, atol, equal_nan=False)

Parameters:

  • arr1: 1st array input
  • arr2:  2nd array input
  • rtol:  relative tolerance
  • atol: absolute tolerance
  • equal_nan: Whether to compare NaN’s as equal. If True, NaN’s in arr1 is considered equal to NaN’s in arr2

Return Value:

True if the two arrays are equal within the given tolerance; otherwise, it is false.

Examples of the allclose method:

1) Basic Numpy allclose() Example:

import numpy as np
a=[1.67,3.56]
b=[1.68,3.56]
print(np.allclose(a,b))

Output & Explanation:

False

As both elements’ first element are not equal, it returns False.

2) NumPy allclose() with relative tolerance:

import numpy as np

arr1 = [1e10,1e-8]
arr2 = [1.00001e10,1e-9]

print(np.allclose(arr1, arr2,rtol=0.1,atol=0.1) )

Output & Explanation:

True

Here, we have used the relative tolerance as 0.1 and the absolute tolerance as 0.1. In the given tolerance range, thearray elements are the same; hence, it returns True.

3) Array having NaN value:

import numpy as np
print(np.allclose([2.0, np.nan], [2.0, np.nan]))

Output & Explanation:

False

As the equal_nan parameter is not set as True, the nan values of both arrays are considered different. As a result, the output is False.

4) Array having NaN value with equal_nan value set as True:

import numpy as np
print(np.allclose([2.0, np.nan], [2.0, np.nan],equal_nan=True))

Output & Explanation:

True

Since we have now used the equal_nan parameter as True, the NaN value of both arrays are considered equal, so the output is True.

Difference between NumPy allclose() & isclose():

NumPy allclose()NumPy isclose()
import numpy as np
a=[1e10,1.002e10]
b=[1e10,1.003e10]

print(np.allclose(a,b))
import numpy as np
a=[1e10,1.002e10]

b=[1e10,1.003e10]
print(np.isclose(a,b))
False[ True False]

Conclusion:

With this article, we come to an end of this article. Here, we saw some illustrated examples to clear our concept on NumPy allclose() method.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments