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.
8 Answers
789
votes
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.
69
votes
31
votes
27
votes
25
votes
Another, less convenient, way to do it is to use Decimal class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
14
votes
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()
math.infis useful as an initial value in optimisation problems, because it works correctly with min, eg.min(5, math.inf) == 5. For example, in shortest path algorithms, you can set unknown distances tomath.infwithout needing to special caseNoneor assume an upper bound9999999. Similarly, you can use-math.infas a starting value for maximisation problems. - Colonel Panic