如何在Python中表示一个无限的数?

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

解决办法

在Python中,你可以这样做。

test = float("inf")

在Python 3.5中,你可以这样做。

import math
test = math.inf

然后。

test > 1
test > 10000
test > x

将永远是真的。当然,除非正如所指出的,x也是无穷大或"nan"("不是一个数字")。

另外(仅Python 2.x),在与Ellipsis的比较中,float(inf)较小,例如

float('inf') < Ellipsis

将返回true。

评论(7)

我不知道你在做什么,但是float("inf")给你一个浮点数Infinity,它比任何其他数字都大。

评论(0)

另一种不太方便的方法是使用Decimal类。

from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
评论(11)