gpt4 book ai didi

python "is"返回 True 但 "=="返回 False

转载 作者:行者123 更新时间:2023-11-28 19:39:33 27 4
gpt4 key购买 nike

只要“is”返回 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

编辑:

float nan 的 3 个表达式只是旧 numpy 版本的遗留物还是它们有其​​他用途?

最佳答案

不,不适用于 NaN .您发现了其中一个异常(exception)。根据IEEE 754 , NaN 不等于任何东西,甚至不等于它自己:

A comparison with a NaN always returns an unordered result even when comparing with itself.

不仅仅是 numpy 的行为是这样的:

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

根据 IEEE 标准实现浮点运算的任何编程语言也是如此。

多个拼写是为了匹配名称的常见大小写。它是 Not a Number 的缩写,不同的人对该缩写的首字母大写不同。

is 对于同一个对象总是 True,但是 == 甚至不能保证返回 bool 值。来自__eq__ documentation :

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

关于python "is"返回 True 但 "=="返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21824846/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com