w3resource

NumPy: Create an element-wise comparison (equal, equal within a tolerance) of two given arrays


Element-Wise Comparison (Equal/Tolerance)

Write a NumPy program to create an element-wise comparison (equal, equal within a tolerance) of two given arrays.

This NumPy program performs element-wise comparisons between two given arrays to determine equality and near-equality within a specified tolerance. By leveraging NumPy's array operations and tolerance parameters, it provides a precise method for checking if elements in the arrays are exactly equal or approximately equal within a defined range.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating NumPy arrays 'x' and 'y' containing numbers for comparison
x = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100])
y = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100.000001])

# Printing a message indicating the original numbers stored in arrays 'x' and 'y'
print("Original numbers:")
print(x)
print(y)

# Performing element-wise comparison (equal) between arrays 'x' and 'y', and printing the result
print("Comparison - equal:")
print(np.equal(x, y))

# Checking if arrays 'x' and 'y' are element-wise equal within a tolerance, and printing the result
print("Comparison - equal within a tolerance:")
print(np.allclose(x, y)) 

Output:

Original numbers:
[  72   79   85   90  150 -135  120  -10   60  100]
[  72.         79.         85.         90.        150.       -135.
  120.        -10.         60.        100.000001]
Comparison - equal:
[ True  True  True  True  True  True  True  True  True False]
Comparison - equal within a tolerance:
True                       

Explanation:

At first we declare two arrays x = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100]): and y = np.array([72, 79, 85, 90, 150, -135, 120, -10, 60, 100.000001]).

print(np.equal(x, y)): Here, the np.equal() function compares the elements of 'x' and 'y' element-by-element and checks whether they are equal.The function returns a boolean array [True, True, True, True, True, True, True, True, True, False], which is printed to the console. The last element is False because 100 is not exactly equal to 100.000001.

print(np.allclose(x, y)): This line uses the np.allclose() function to check if the two arrays are element-wise equal within a given tolerance (default relative tolerance rtol=1e-9, absolute tolerance atol=1e-12). In this case, the difference between the last elements (100 and 100.000001) is within the default tolerance, so the function returns True.

Python-Numpy Code Editor: