python - Test if two numpy arrays are (close to) equal, including shape -


i want test if 2 numpy arrays (close to) equal, i've been using np.allclose function. problem is, returns true if given two-dimensional matrix , three-dimensional matrix of equal elements.

import numpy np  x = np.array([[3.14159265, -0.1], [-0.1, 0.1]])  y = np.array([[math.pi, -0.1], [-0.1, 0.1]])  z1 = np.array([[[3.14159265, -0.1], [-0.1, 0.1]],               [[3.14159265, -0.1], [-0.1, 0.1]]]) z2 = np.array([[[math.pi, -0.1], [-0.1, 0.1]],               [[math.pi, -0.1], [-0.1, 0.1]]])     np.allclose(x,y) # returns true, expected  np.allclose(x,z1) # returns true, though matrices different shapes. unwanted. 

now, know np.array_equal, compares elements , shape, doesn't allow me test if elements close, if equal. instance,

np.array_equal(x,y) 

returns false

is there function can use return true (x,y) , (z1,z2) false (x,z1) in case?

what's happening allclose broadcasts input. allows comparisons shaped arrays (e.g. 3 , [3, 3, 3]) following broadcasting rules.


for purposes, have @ numpy.testing functions, np.testing.assert_allclose or assert_array_almost_equal, check shape values. (i don't remember difference between 2 offhand, relates way calculate floating point differences.)

these particularly handy if you're using assert-based unit testing.

most (all?) of numpy.testing.assert_* functions check array shape value equality.

for example:

in [1]: import numpy np  in [2]: np.testing.assert_allclose([1], [[1]]) 

which yields:

assertionerror: not equal tolerance rtol=1e-07, atol=0  (shapes (1,), (1, 1) mismatch)  x: array([1])  y: array([[1]]) 

another useful (and not documented be) thing know these functions compare nan's equal.

for example, succeed:

in [3]: np.testing.assert_allclose([np.nan], [np.nan]) 

while numpy.allclose return false same case:

in [4]: np.allclose([np.nan], [np.nan]) out[4]: false 

on side note, numpy.isclose (but not allclose) has equal_nan kwarg control this.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -