简体   繁体   English

python“is”返回True但“==”返回False

[英]python “is” returns True but “==” returns False

shouldn't "==" return True as long as "is" returns True? 只要“是”返回True,不应该“==”返回True?

In [101]: np.NAN is np.nan is np.NaN
Out[101]: True

In [102]: np.NAN == np.nan 
Out[102]: False

In [103]: np.NaN == np.nan
Out[103]: False

In [104]: np.NaN == np.NAN
Out[104]: False

EDIT: 编辑:

Are the 3 expressions for float nan just legacy of old numpy versions or do they have other usage? float nan的3个表达式只是旧numpy版本的遗留物还是有其他用法?

No, not for NaN . 不,不是NaN You have found one of the exceptions. 您已找到其中一个例外情况。 According to IEEE 754 , NaN is not equal to anything, not even itself: 根据IEEE 754 ,NaN不等于任何东西,甚至不是自己:

A comparison with a NaN always returns an unordered result even when comparing with itself. 与NaN进行比较时,即使与自身进行比较,也会返回无序结果

Not just numpy behaves like this: 不只是numpy表现得像这样:

>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False

as will any programming language that implements floating point arithmetic according to the IEEE standard. 任何根据IEEE标准实现浮点运算的编程语言也是如此。

The multiple spellings are there to match the common capitalisations for the name. 多个拼写可以匹配名称的共同首都。 It is an abbreviation for Not a Number and different people capitalise the abbreviation differently. 它是Not a Number的缩写,不同的人将缩写大写不同。

is is always going to be True for the same object, but == is not even guaranteed to return a boolean. 对于同一个对象, is is总是为True ,但是==甚至不能保证返回一个布尔值。 From the __eq__ documentation : __eq__文档

By convention, False and True are returned for a successful comparison. 按照惯例,返回FalseTrue以进行成功比较。 However, these methods can return any value, so if the comparison operator is used in a Boolean context (eg, in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false. 但是,这些方法可以返回任何值,因此如果在布尔上下文中使用比较运算符(例如,在if语句的条件下),Python将对值调用bool()以确定结果是true还是false 。

The standard for floating point (IEEE 754) requires that any comparison of NaN values returns not equal. 浮点标准(IEEE 754)要求NaN值的任何比较返回不相等。 This is common to any programming language that claims to implement IEEE 754, not just Python. 这对于声称实现IEEE 754的任何编程语言都很常见,而不仅仅是Python。

See also Wikipedia's description of a NaN . 另请参阅Wikipedia 对NaN描述

Quoting from the docs , 引用文档

Special values defined in numpy: nan, inf, numpy中定义的特殊值:nan,inf,

NaNs can be used as a poor-man's mask (if you don't care what the original value was) NaNs可以用作穷人的面具(如果你不关心原始值是什么)

Note: cannot use equality to test NaNs. 注意: 不能使用相等来测试NaN。 Eg: 例如:

... ...

np.nan == np.nan # is always False! np.nan == np.nan#总是错的! Use special numpy functions instead. 请改用特殊的numpy函数。 False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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