[python] How can I represent an infinite number in 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.

This question is related to python infinite infinity

The answer is


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


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

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

Also if you use SymPy you can use sympy.oo

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

etc.


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

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

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