简体   繁体   中英

python nan != nan

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = float('nan')
>>> id(x) == id(x)
True
>>> x == x
False

I'm interested in how nan != nan in python. And just to clarify, I know nan is supposed to behave like that by definition, I'm asking about how not about why. Where is that implemented? Is there any other object which behaves like that?

Not A Number (NaN) is unequal with anything. To detect it, use math.isnan . And an object like this is quite easy to define:

class A(object):
    def __eq__(self, other):
        return False

    def __ne__(self, other):
        return True

The reason why this is is quite simple. CPython follows the IEEE 754 standard for floating point math. NaN is a floating point value for which IEEE 754 dictates that it is not equal to any other floating point value.

The machine code that implements floating point operations handles the result of operations with NaN. For the x86 processor series this is usually achieved using x87 coprocessor instructions, although for earlier x86 processors where an x87 coprocessor was not always present a compiler usually provided emulation code.

For the "where" part of your questions, look starting at line 391 in Objects/floatobject.c in the Python 2.7.3 source tree. A brief discussion is given about the behavior of NaN == NaN with the implementation following.

With respect to other cases that exhibit similar behavior, it is certainly possible. I have not done an exhaustive search of the libraries however, so I can't give a definitive answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM