简体   繁体   English

Python的==是否等于浮点数的对等关系?

[英]Is Python's == an equivalence relation on the floats?

In native Python, without using NumPy (for which numpy.nan != numpy.nan ) there is no NaN, so am I right in thinking that Python's floating point == is reflexive? 在本机Python中,如果不使用NumPy(对于numpy.nan != numpy.nan ),则没有NaN,所以我认为Python的浮点==具有反射性是对的吗? Then since it is symmetric ( a == b implies b == a ) and transitive (if a==b and b==c then a==c ), can we say that Python's == is an equivalence relation on the float s? 然后,由于它是对称的( a == b意味着b == a )并且是可传递的(如果a==bb==ca==c ),我们可以说Python的==float上的等价关系s?

EDIT: OK, so I learned that there is a NaN: float('nan') (thanks @unutbu) which will propagate through various operations, but does any native Python method return it (rather than raising an Exception) without me introducing it by this assignment? 编辑:好的,让我了解到一个楠: float('nan')感谢@unutbu)将通过各种操作传播,但是否有任何原生的Python方法返回它(而不是抛出一个异常),而我将其引入通过这项任务?

== is reflexive for all numbers, zero, -zero, ininity, and -infinity, but not for nan. ==对于所有数字(零,-零,ininity和-infinity)是自反的,但对于nan则不自反。

You can get inf , -inf , and nan in native Python just by arithmetic operations on literals, like below. 您可以通过对文字进行算术运算来在本地Python中获得inf-infnan ,如下所示。

These behave correctly, as in IEEE 754 and without math domain exception: 它们的行为正确,如在IEEE 754中并且没有数学域异常:

>>> 1e1000 == 1e1000
True
>>> 1e1000/1e1000 == 1e1000/1e1000
False

1e1000 is a very big number, so float and double represent it as an infinity. 1e1000是一个非常大的数字,因此float和double将其表示为无穷大。

  • infinity is equal to infinity 无限等于无限
  • infinity divided by infinity is not a number 无限除以无限不是数字
  • not a number != not a number 不是数字!=不是数字

Floating-point arithmetic in Python also works OK for infinity minus infinity etc.: Python中的浮点算术对于无穷负无穷等也可以工作:

>>> x = 1e1000
>>> x
inf
>>> x+x
inf
>>> x-x
nan
>>> x*2
inf
>>> x == x
True
>>> x-x == x-x
False
>>> 

And for the zero and minus zero case: 对于零和负零的情况:

>>> inf = float("inf")
>>> 1/inf
0.0
>>> -1/inf
-0.0
>>> -1/inf == 1/inf
True
>>> 

float('nan') exists in native Python and float('nan') != float('nan') . float('nan')存在于本机Python中,并且float('nan') != float('nan') So no, == is not an equivalence relation since it lacks reflexivity: 所以不, ==不是等价关系,因为它缺乏自反性:

In [40]: float('nan') == float('nan')
Out[40]: False

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

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