我如何在python中表示一个无限的数字?无论你在程序中输入哪个数字,都不应该大于这个表示无穷大的数字。
当前回答
在python2。x有一个肮脏的黑客达到了这个目的(千万不要使用它,除非绝对必要):
None < any integer < any string
因此,检查i < "对于任何整数i都为真。
它在python3中已被合理地弃用。现在这样的比较以
TypeError: unorderable types: str() < int()
其他回答
从Python 3.5开始,你可以使用math.inf:
>>> import math
>>> math.inf
inf
如果你使用SymPy,你也可以使用symphony .oo
>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan
etc.
对于正无穷
pos_inf_val = float("infinity")
对于负无穷
neg_inf_val = float("-infinity")
另一种不太方便的方法是使用Decimal class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
在Python中,你可以这样做:
test = float("inf")
在Python 3.5中,你可以:
import math
test = math.inf
然后:
test > 1
test > 10000
test > x
永远是真的。当然,如前所述,除非x也是无穷大或“nan”(“不是一个数字”)。
此外(Python 2。x ONLY),与Ellipsis相比,float(inf)较小,例如:
float('inf') < Ellipsis
返回true。