我只想弄清楚这些结果背后的逻辑:

>>>nan = float('nan')
>>>nan == nan
False
# I understand that this is because the __eq__ method is defined this way
>>>nan in [nan]
True
# This is because the __contains__ method for list is defined to compare the identity first then the content?

但在这两种情况下,我认为在幕后调用函数 PyObject_RichCompareBool 对吗?为什么有区别?他们不应该有相同的行为吗?

最佳答案


== 从不直接调用浮点对象上的 PyObject_RichCompareBool,浮点数有自己的 rich_compare 方法(调用 __eq__ ),根据传递给它的参数可能会或可能不会调用 PyObject_RichCompareBool

 /* Comparison is pretty much a nightmare.  When comparing float to float,
 * we do it as straightforwardly (and long-windedly) as conceivable, so
 * that, e.g., Python x == y delivers the same result as the platform
 * C x == y when x and/or y is a NaN.
 * When mixing float with an integer type, there's no good *uniform* approach.
 * Converting the double to an integer obviously doesn't work, since we
 * may lose info from fractional bits.  Converting the integer to a double
 * also has two failure modes:  (1) a long int may trigger overflow (too
 * large to fit in the dynamic range of a C double); (2) even a C long may have
 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
 * 63 bits of precision, but a C double probably has only 53), and then
 * we can falsely claim equality when low-order integer bits are lost by
 * coercion to double.  So this part is painful too.
 */

static PyObject*
float_richcompare(PyObject *v, PyObject *w, int op)
{
    double i, j;
    int r = 0;

    assert(PyFloat_Check(v));
    i = PyFloat_AS_DOUBLE(v);

    /* Switch on the type of w.  Set i and j to doubles to be compared,
     * and op to the richcomp to use.
     */
    if (PyFloat_Check(w))
        j = PyFloat_AS_DOUBLE(w);

    else if (!Py_IS_FINITE(i)) {
        if (PyInt_Check(w) || PyLong_Check(w))
            /* If i is an infinity, its magnitude exceeds any
             * finite integer, so it doesn't matter which int we
             * compare i with.  If i is a NaN, similarly.
             */
            j = 0.0;
        else
            goto Unimplemented;
    }
...

另一方面, list_contains 直接在项目上调用 PyObject_RichCompareBool 因此在第二种情况下你会得到 True 。

请注意,这仅适用于 CPython,PyPy 的 list.__contains__ 方法似乎只是通过调用它们的 __eq__ 方法来比较项目:
$~/pypy-2.4.0-linux64/bin# ./pypy
Python 2.7.8 (f5dcc2477b97, Sep 18 2014, 11:33:30)
[PyPy 2.4.0 with GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>> nan = float('nan')
>>>> nan == nan
False
>>>> nan is nan
True
>>>> nan in [nan]
False

关于Python:列表中 Nan 的相等性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27616824/

10-13 02:54