Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between allclose() and array_equal()?

Tags:

python

numpy

Numpy has the following methods:

allclose() - Assuming identical shape of the arrays and a tolerance for the comparison of values

array_equal() - Checking both the shape and the element values, no tolerance (values have to be exactly equal)

I can't seem to find any difference between them. Any examples?


1 Answers

np.allclose is designed to be used with arrays of floating point numbers. Floating point calculations have inherent precision loss, so you can often find yourself with numbers which should be equal but differ by a very tiny amount.

On the other hand, np.array_equal is designed to be used with arrays of integers and only checks for exact equality.

Consider the following example which generates an array of 100 floating point numbers, divides it by 1.5, and then multiplies it by 1.5. Due to precision loss the arrays are no longer exactly equal but are still close within a very small tolerance.

arr = np.random.rand(1000)

arr2 = arr / 1.5
arr2 = arr2 * 1.5

print(np.array_equal(arr, arr2))
# False

print(np.allclose(arr, arr2, atol=1e-16, rtol=1e-16))
# True
like image 156
Chris Mueller Avatar answered Sep 22 '25 12:09

Chris Mueller