我如何在python中表示一个无限的数字?无论你在程序中输入哪个数字,都不应该大于这个表示无穷大的数字。


当前回答

总的来说,无穷有两种定义。

对于正无穷

posVal1 = math.inf
posVal2 = float("inf")

对于负无穷

negVal1 = -math.inf
negVal2 = float("-inf")

其他回答

似乎没有人明确提到负无穷,所以我想我应该加上它。

对于负无穷:

-math.inf

对于正无穷(为了完整起见):

math.inf

从Python 3.5开始,你可以使用math.inf:

>>> import math
>>> math.inf
inf

我不知道你到底在做什么,但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。

如果你使用SymPy,你也可以使用symphony .oo

>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan

etc.