NaNs在Numpy中的比较相等

NPE*_*NPE 6 python numpy nan ieee-754 multidimensional-array

请考虑以下脚本:

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
Run Code Online (Sandbox Code Playgroud)

在我的机器上打印出来

[False]
[ True]
Run Code Online (Sandbox Code Playgroud)

第一种情况很明显(根据IEEE-754),但在第二种情况下会发生什么?为什么这两个NaN比较平等?

Python 2.7.3,Darwin上的Numpy 1.6.1.

beh*_*uri 7

在较新版本的numpy上,您会收到以下警告:

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.
Run Code Online (Sandbox Code Playgroud)

我的猜测是numpy正在使用idtest作为快捷方式,对于object类型,然后再回到__eq__测试,从那以后

>>> id(np.nan) == id(np.nan)
True
Run Code Online (Sandbox Code Playgroud)

它返回true.

如果你使用float('nan')而不是np.nan结果会有所不同:

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • 你的例子有问题:`id(4.5)== id(float('4.5'))`也是'False`. (2认同)