python nan != nan

大城市里の小女人 提交于 2019-12-18 17:07:07

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/13003202/python-nan-nan

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!