The Python Oracle

How can I represent an infinite number in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Question
00:25 Accepted answer (Score 896)
01:08 Answer 2 (Score 109)
01:22 Answer 3 (Score 93)
01:46 Answer 4 (Score 33)
02:04 Thank you

--

Full question
https://stackoverflow.com/questions/7781...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #infinite #infinity

#avk47



ACCEPTED ANSWER

Score 948


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.




ANSWER 2

Score 116


Since Python 3.5 you can use math.inf:

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



ANSWER 3

Score 35


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




ANSWER 4

Score 34


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