Test if two numpy arrays are (close to) equal, including shape
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Test If Two Numpy Arrays Are (Close To) Equal, Including Shape
00:55 Accepted Answer Score 19
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/3287...
--
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.