The Python Oracle

How can I represent an infinite number in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 How Can I Represent An Infinite Number In Python?
00:18 Accepted Answer Score 945
00:43 Answer 2 Score 116
00:54 Answer 3 Score 108
01:10 Answer 4 Score 35
01:23 Answer 5 Score 34
01:33 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.