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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.