2017-03-11 8 views
0

次のような方法を説明できる人はいますか?私はPython 2と3で試してみましたが、同じ結果が得られました。 nanは常に同じではないとは限りませんか?または、ポインタを比較している場合、ポインタが常に等しいとは限りませんか?どうしたの?Falseを比較すると浮動小数点数を比較しますが、タプルではnansを比較します。

>>> n = float('nan') 
>>> n == n 
False 
>>> (n,) == (n,) 
True 

答えて

1

n == nの場合、float番号の比較方法を使用します。 (n,) == (n,)について

、それはそれがオブジェクトの比較メソッドを呼び出し

/* 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; 
} 

、タプルの比較メソッドを呼び出します。 2つのオブジェクトが同じ場合は直ちにtrueを返します。

/* 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; 
} 
+0

Gotcha。私は '=='が 'PyObject_RichCompareBool'を呼び出さないことに気づいていませんでした。 –

関連する問題