我如何在python中表示一个无限的数字?无论你在程序中输入哪个数字,都不应该大于这个表示无穷大的数字。
当前回答
另一种不太方便的方法是使用Decimal class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
其他回答
如果你使用SymPy,你也可以使用symphony .oo
>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan
etc.
总的来说,无穷有两种定义。
对于正无穷
posVal1 = math.inf
posVal2 = float("inf")
对于负无穷
negVal1 = -math.inf
negVal2 = float("-inf")
在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。
另一种不太方便的方法是使用Decimal class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
NumPy库中有一个无穷大:from NumPy import inf。要得到负无穷大,可以简单地写入-inf。