Python nan浮点标识比较False,但元组中的nan比较True
有人能解释一下以下是怎么可能的吗?我在Python2和Python3中进行了尝试,得到了相同的结果。Python nan浮点标识比较False,但元组中的nan比较True,python,reference,comparison,Python,Reference,Comparison,有人能解释一下以下是怎么可能的吗?我在Python2和Python3中进行了尝试,得到了相同的结果。nans不应该总是比较不相等吗?或者,如果是比较指针,指针不应该总是比较相等吗?发生什么事了 >>> n = float('nan') >>> n == n False >>> (n,) == (n,) True 对于n==n,它使用浮点数的比较方法 对于(n,)==(n,),它调用tuple的比较方法 /* Search for the
nan
s不应该总是比较不相等吗?或者,如果是比较指针,指针不应该总是比较相等吗?发生什么事了
>>> n = float('nan')
>>> n == n
False
>>> (n,) == (n,)
True
对于
n==n
,它使用浮点数的比较方法
对于(n,)==(n,)
,它调用tuple的比较方法
/* Search for the first index where items are different.
* Note that because tuples are immutable, it's safe to reuse
* vlen and wlen across the comparison calls.
*/
for (i = 0; i < vlen && i < wlen; i++) {
int k = PyObject_RichCompareBool(vt->ob_item[i],
wt->ob_item[i], Py_EQ);
if (k < 0)
return NULL;
if (!k)
break;
}
明白了。我没有意识到
==
不会调用PyObject\u richcomarebool
。
/* Quick result when objects are the same.
Guarantees that identity implies equality. */
if (v == w) {
if (op == Py_EQ)
return 1;
else if (op == Py_NE)
return 0;
}