How can I represent an infinite number in Python?

一世执手 提交于 2019-11-27 09:58:06

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.

Since Python 3.5 you can use math.inf:

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

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

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

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

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

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

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()

Also if you use sympy you can use sympy.oo

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

etc.

user2719152

first of all type of float('inf') is float though it can be used for comparison purpose but it is considerably slow to compare against it. So if you are comparing a large list of number against float('inf') then be careful to pick it. I am not sure about the performance of "math.inf".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!