2

I want whether two numpy arrays with complex numbers containing NaN are exactly equal.

Specifically, I want to verify that for NaN, not only is there a NaN in both arrays but also that the real and imaginary part of the NaN match in value.

Does anybody know whether assert_array_equal does this or do I have to check this myself?

ARF
  • 7,420
  • 8
  • 45
  • 72

2 Answers2

2

Numpy just checks whether there are NaN values in the same positions and uses np.isnan for that purpose. Here it doesn't matter whether the real or imaginary part contains the NaN value:

>>> np.isnan(np.sqrt(-1.) + 1j)
True
>>> np.isnan(np.sqrt(-1.) * 1j)
True

Similarly for two arrays a and b:

>>> a = np.zeros(3, dtype=np.complex128)
>>> b = a.copy()
>>> a[0] = np.sqrt(-1.) + 1j
>>> b[0] = np.sqrt(-1.) * 1j
>>> a
array([nan+1.j,  0.+0.j,  0.+0.j])
>>> b
array([nan+nanj,  0. +0.j,  0. +0.j])
>>> np.testing.assert_array_equal(a, b) is None
True
a_guest
  • 34,165
  • 12
  • 64
  • 118
2

From comparing numpy arrays containing NaN

def eq(a, b):
    return np.all((a == b) | (np.isnan(a) & np.isnan(b)))

To compare complex numbers just check the equality of real and imaginary parts. For example:

a = np.array([1+2j, 3+4j, np.nan+6j])
b = np.array([1+2j, 3+4j, np.nan+5j])

eq(a.real, b.real) & eq(a.imag, b.imag)
False

Edit: Or you can use np.allclose(a.real, b.real, equal_nan=True) & np.allclose(a.imag, b.imag, equal_nan=True).

Andreas K.
  • 9,282
  • 3
  • 40
  • 45