Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I represent an infinite number in Python?

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

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

For negative infinity:

-math.inf

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

math.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.


There is an infinity in the NumPy library: from numpy import inf. To get negative infinity one can simply write -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')