Home > Enterprise >  How to check if two NumPy arrays are approximately equal?
How to check if two NumPy arrays are approximately equal?

Time:09-22

np.isclose (or np.allclose) check if two arrays are approximately equal. But they both raise an exception if the inputs are not of the same shape. I wonder if there is a library function that can be used for checking 'approximate' equality of two arbitrary arrays? I.e., something like

def allclose(x, y, *args, **kwargs):
    return x.shape == y.shape and np.allclose(x, y, *args, **kwargs)

In fact, for 'exact' equality np.array_equal already does the job (by returning False on arrays of different size, instead of raising an exception).

CodePudding user response:

There isn't such a function, and for a particular reason: It allows broadcasting. That means you can compare two arrays of different shapes as long as they are broadcastable.

a = np.array([[1, 2], [1, 2]],)
b = np.array([1, 2])

np.isclose(a, b)          # row-wise comparison
# array([[ True,  True],
#        [ True,  True]])
np.isclose(a, b[:, None]) # column-wise comparison
# array([[ True, False],
#        [False,  True]])

So if your function allows broadcasting you want to know whether the two arrays were different, or just in an incompatible shape.

So if you want to retain broadcast-ability, I would suggest

def allclose(x, y, *args, **kwargs):
    try:
        return np.allclose(x, y, *args, **kwargs)
    except ValueError:
        return False
  • Related