Closed
Description
As expected np.testing.assert_allclose(np.array([1.0, 1.0]), np.array([1.0]))
raises an assertion
but np.allclose(np.array([1.0, 1.0]), np.array([1.0]))
returns True. This seems to be because np.allclose
does not check that the shapes of the input is identical before subtracting the 2 arrays and ends up broadcasting the one element array to the shape of the 2 element array. And therefore np.allclose(np.array([1.0, 1.0, 1.0]), np.array([1.0, 1.0]))
raises a value error when failing to broadcast
ValueError Traceback (most recent call last)
<ipython-input-7-31d9eb09a824> in <module>()
----> 1 np.allclose(np.array([1.0, 1.0, 1.0]), np.array([1.0, 1.0]))
~/.pyenv/versions/3.6.3/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/numeric.py in allclose(a, b, rtol, atol, equal_nan)
2457
2458 """
-> 2459 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2460 return bool(res)
2461
~/.pyenv/versions/3.6.3/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/numeric.py in isclose(a, b, rtol, atol, equal_nan)
2539 yfin = isfinite(y)
2540 if all(xfin) and all(yfin):
-> 2541 return within_tol(x, y, atol, rtol)
2542 else:
2543 finite = xfin & yfin
~/.pyenv/versions/3.6.3/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/numeric.py in within_tol(x, y, atol, rtol)
2522 def within_tol(x, y, atol, rtol):
2523 with errstate(invalid='ignore'):
-> 2524 result = less_equal(abs(x-y), atol + rtol * abs(y))
2525 if isscalar(a) and isscalar(b):
2526 result = bool(result)
ValueError: operands could not be broadcast together with shapes (3,) (2,)
Is it intentional that np.allclose
does not compare shapes? From the docstring of assert_allclose I would expect them to behave identically (apart from the different abs and rel tol)
Tested with numpy 1.13.3 and 1.12.0