问题:如何在Python中表示一个无限数?

如何在python中表示无穷大?无论您在程序中输入哪个数字,任何数字都不得大于此无穷大表示形式。

How can I represent an infinite number in python? No matter which number you enter in the program, no number should be greater than this representation of infinity.


回答 0

在Python中,您可以执行以下操作:

test = float("inf")

在Python 3.5中,您可以执行以下操作:

import math
test = math.inf

然后:

test > 1
test > 10000
test > x

永远是真的。当然,除非指出,否则x也是无穷大或“ nan”(“非数字”)。

另外(Python的ONLY 2.X)中,在比较Ellipsisfloat(inf)较小,例如:

float('inf') < Ellipsis

将返回true。

In Python, you can do:

test = float("inf")

In Python 3.5, you can do:

import math
test = math.inf

And then:

test > 1
test > 10000
test > x

Will always be true. Unless of course, as pointed out, x is also infinity or “nan” (“not a number”).

Additionally (Python 2.x ONLY), in a comparison to Ellipsis, float(inf) is lesser, e.g:

float('inf') < Ellipsis

would return true.


回答 1

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

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

Since Python 3.5 you can use math.inf:

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

回答 2

似乎没有人明确提到负无穷大,因此我认为应该添加它。

对于正无穷大(仅出于完整性考虑):

math.inf

对于负无穷大:

-math.inf

No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.

For positive infinity (just for the sake of completeness):

math.inf

For negative infinity:

-math.inf

回答 3

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

I don’t know exactly what you are doing, but float("inf") gives you a float Infinity, which is greater than any other number.


回答 4

有一个在与NumPy库的无边:from numpy import inf。要获得负无穷大,可以简单地写-inf

There is an infinity in the NumPy library: from numpy import inf. To get negative infinity one can simply write -inf.


回答 5

另一种较不方便的方法是使用Decimal类:

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

Another, less convenient, way to do it is to use Decimal class:

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

回答 6

在python2.x中,有一个肮脏的hack可以达到这个目的(除非绝对必要,否则不要使用它):

None < any integer < any string

因此,检查i < ''适用True于任何整数i

在python3中已合理弃用了它。现在这样的比较最终

TypeError: unorderable types: str() < int()

In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary):

None < any integer < any string

Thus the check i < '' holds True for any integer i.

It has been reasonably deprecated in python3. Now such comparisons end up with

TypeError: unorderable types: str() < int()

回答 7

另外,如果您使用SymPy,则可以使用 sympy.oo

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

等等

Also if you use SymPy you can use sympy.oo

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

etc.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。