cjm2671
cjm2671

Reputation: 19496

Why does assert np.nan == np.nan cause an error?

If

assert 1 == 1

is fine, then why does:

assert np.nan == np.nan

cause an assertion error?

What's even more confusing, this is OK:

assert np.nan != np.nan

What's the best way to test for nan?

Upvotes: 18

Views: 9506

Answers (2)

EdChum
EdChum

Reputation: 394389

NaN has the property that it doesn't equal itself, you should use np.isnan to test NaN values, here np.isnan(np.nan) will yield True:

In[5]:
np.nan == np.nan

Out[5]: False

In[6]:
np.nan != np.nan

Out[6]: True

In[7]:
np.isnan(np.nan)

Out[7]: True

Upvotes: 26

Yann Vernier
Yann Vernier

Reputation: 15887

Use np.isnan(value). NaN doesn't compare equal to itself because it indicates a failure, and might not have been produced the same way. I'm not sure why isnan is missing in the CPython documentation, but it's present in math for both CPython 3.4 and 2.7, and as a ufunc in numpy.

Upvotes: 3

Related Questions