Test if two numpy arrays are (close to) equal, including shape
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs
--
Chapters
00:00 Question
01:22 Accepted answer (Score 17)
03:17 Thank you
--
Full question
https://stackoverflow.com/questions/3287...
Accepted answer links:
[broadcasting rules]: http://docs.scipy.org/doc/numpy/user/bas...
[np.testing.assert_allclose]: http://docs.scipy.org/doc/numpy/referenc...
[assert_array_almost_equal]: http://docs.scipy.org/doc/numpy/referenc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy
#avk47
ACCEPTED ANSWER
Score 19
What's happening is that allclose broadcasts its input. This allows comparisons with similarly shaped arrays (e.g. 3 and [3, 3, 3]) following the broadcasting rules.
For your purposes, have a look at the numpy.testing functions, specifically np.testing.assert_allclose or assert_array_almost_equal, which will check for shape as well as values. (I don't remember the difference between those two offhand, but it relates to the way they calculate floating point differences.)
These are particularly handy if you're using assert-based unit testing.
Most (all?) of the numpy.testing.assert_* functions check for array shape as well as value equality.
For example:
In [1]: import numpy as np
In [2]: np.testing.assert_allclose([1], [[1]])
Which yields:
AssertionError:
Not equal to tolerance rtol=1e-07, atol=0
(shapes (1,), (1, 1) mismatch)
x: array([1])
y: array([[1]])
Another useful (and currently not as well documented as it could be) thing to know about these functions is that they compare NaN's as equal.
For example, this will succeed:
In [3]: np.testing.assert_allclose([np.nan], [np.nan])
While numpy.allclose will return False for the same case:
In [4]: np.allclose([np.nan], [np.nan])
Out[4]: False
On a side note, numpy.isclose (but not allclose) has an equal_nan kwarg to control this.