Skip to content

Commit

Permalink
BUG: Fixed maximum relative error reporting in assert_allclose (numpy…
Browse files Browse the repository at this point in the history
…gh-13802)

Fixed maximum relative error reporting in assert_allclose:

In cases where the two arrays have zeros at the same positions it will
no longer report nan as the max relative error
  • Loading branch information
CakeWithSteak authored and maxwell-aladago committed Sep 6, 2019
1 parent f08c91e commit 0710757
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions numpy/testing/_private/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
header='', precision=6, equal_nan=True,
equal_inf=True):
__tracebackhide__ = True # Hide traceback for py.test
from numpy.core import array, array2string, isnan, inf, bool_, errstate
from numpy.core import array, array2string, isnan, inf, bool_, errstate, all

x = array(x, copy=False, subok=True)
y = array(y, copy=False, subok=True)
Expand Down Expand Up @@ -807,7 +807,12 @@ def func_assert_same_pos(x, y, func=isnan, hasval='nan'):

# note: this definition of relative error matches that one
# used by assert_allclose (found in np.isclose)
max_rel_error = (error / abs(y)).max()
# Filter values where the divisor would be zero
nonzero = bool_(y != 0)
if all(~nonzero):
max_rel_error = array(inf)
else:
max_rel_error = (error[nonzero] / abs(y[nonzero])).max()
if error.dtype == 'object':
remarks.append('Max relative difference: '
+ str(max_rel_error))
Expand Down
9 changes: 9 additions & 0 deletions numpy/testing/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,15 @@ def test_equal_nan_default(self):
assert_array_less(a, b)
assert_allclose(a, b)

def test_report_max_relative_error(self):
a = np.array([0, 1])
b = np.array([0, 2])

with pytest.raises(AssertionError) as exc_info:
assert_allclose(a, b)
msg = str(exc_info.value)
assert_('Max relative difference: 0.5' in msg)


class TestArrayAlmostEqualNulp(object):

Expand Down

0 comments on commit 0710757

Please sign in to comment.