Comparing NaNs in Numpy

Consider the following script:

import numpy as np a = np.array([np.nan], dtype=float) b = np.array([np.nan], dtype=float) print a == b a = np.array([np.nan], dtype=object) b = np.array([np.nan], dtype=object) print a == b 

On my machine it gives out

 [False] [ True] 

The first case is clear ( according to IEEE-754 ), but what happens in the second case? Why are two NaNs compared to peers?

Python 2.7.3, Numpy 1.6.1 on Darwin.

+6
source share
1 answer

In newer versions of numpy you will get this warning:

 FutureWarning: numpy equal will not check object identity in the future. The comparison did not return the same result as suggested by the identity (`is`)) and will change. 

I assume numpy uses id test as a shortcut for object types before returning to the __eq__ test, and since

 >>> id(np.nan) == id(np.nan) True 

it returns true.

if you use float('nan') instead of np.nan , the result will be different:

 >>> a = np.array([np.nan], dtype=object) >>> b = np.array([float('nan')], dtype=object) >>> a == b array([False], dtype=bool) >>> id(np.nan) == id(float('nan')) False 
+7
source

Source: https://habr.com/ru/post/978878/


All Articles