807

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.

5
  • 63
    math.inf is 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 to math.inf without needing to special case None or assume an upper bound 9999999. Similarly, you can use -math.inf as a starting value for maximisation problems. Commented Oct 12, 2016 at 10:59
  • 3
    In most cases, an alternative to using math.inf in optimization problems is to start with the first value. Commented May 30, 2020 at 7:26
  • 4
    Can't help but wonder how so many Python question seems to attract a multitude of ways to do the same thing. How is that Pythonian or compatible with Zen of Python.... Commented Oct 25, 2021 at 14:25
  • 2
    @nyholku agree.. There should be one-- and preferably only one --obvious way to do it. Commented Feb 10, 2022 at 1:17
  • @nyholku It looks to me like the answers here are all substantively suggesting doing the same thing, though. Floating-point infinity is the same built-in object whether you access it as a constant in the math standard library or by asking the float type to parse the string "inf". Commented Jun 2, 2023 at 1:32

14 Answers 14

964

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that infinity is defined in the norm IEEE 754-1985 (en.wikipedia.org/wiki/IEEE_754-1985), which Any modern language will rely on. Another point is that, according to this norm, infinity must (obviously) be a floating-point number. This might explain why Python have chosen this akward syntax.
And you can do -float("inf") to get minus infinity which is smaller than any other number.
120

Since Python 3.5 you can use math.inf:

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

Comments

114

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 

3 Comments

How do float("inf"), math.inf, and np.inf compare? Which one to use when?
@CGFoX Use the first one if you don't want to load packages, that's about the height of it.
@stefanbschneider under the hood they all use the same floating point representation of infinity as specified by the IEEE 754 floating point standard. So they are essentially all the same. On my machine, using timeit, float('inf') took about 185 nanoseconds, whereas the numpy and math versions both took about 70 nanoseconds. This is probably because float('inf') has to parse the string and perform some checks. This small of a time is almost always too small to optimize for, but since they are also quicker to type, I don't see why you would use the float('inf') option
39

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

Comments

36

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

2 Comments

How do float("inf"), math.inf, and np.inf compare? Which one to use when?
The first two are native i.e. require no dependency. np.inf requires the Numpy package. float('inf') is a bit hacky as it involves parsing a string, but on the upside it does not even require an import and the parsing is typically computationally negligible. If you use one of the math packages anyway, though, then just use them. If you happen to use both math and np, then np.inf is the shortest one.
30

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

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

10 Comments

why don't you add why it is less convenient and why anyone should use it?
Let's see: Decimal('Infinity') == float('inf') returns True, so it's pretty much the same.
@afzal_SH float('inf') is float('inf') returns False too
infinity is different even from itself, so your comment didn't make much sense to me, IMHO
float('inf') is float('inf') -> False, just holds that they are different objects with different instances, but not that the internal contents are different -- actually as @nemesisdesign pointed float('int') == float('int') holds to True. This is the same problem like comparing mutable objects like [1,2,3] is [1,2,3] and [1,2,3] == [1,2,3], which are, in order, False and True.. More info see: stackoverflow.com/questions/2988017/…
|
22

Infinity

1. Using float('inf') and float('-inf)

positive_infinity = float('inf') negative_infinity = float('-inf') 

2. Using Python’s math module

import math positive_infinity = math.inf negative_infinity = -math.inf 

3. Integer maxsize

import sys maxSize = sys.maxsize minSize = -sys.maxsize 

4. Using Python’s decimal module

from decimal import Decimal positive_infinity = Decimal('Infinity') negative_infinity = Decimal('-Infinity') 

5. Using Numpy Library

from numpy import inf positive_infinity = inf negative_infinity = -inf 

1 Comment

Upvoted for the sys.maxsize since we often want integers . I wish they had named it maxint instead so it would be easier to remember
19

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

2 Comments

If you really have yo use this, at least wrap it in some readable names like: MIN_INFINITY = None; INFINITY = "inf"; MIN_INFINITY < x < INFINITY
But you don't have to use this.
14

Also if you use SymPy you can use sympy.oo

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

etc.

Comments

4

For Positive Infinity

pos_inf_val = float("infinity") 

For Negative Infinity

neg_inf_val = float("-infinity") 

Comments

0

Representing in python

float("inf") or float("INF") or float("Inf") or float("inF") or float("infinity") or float("Infinity") creates a float object holding

You can also represent -∞ in python

float("-inf") or float("-INF") or float("-Inf") or float("-infinity") creates a float object holding -∞

You can perform arithmetic operations:

infinity = float("inf") ninfinity = float("-inf") nan = float("nan") print(infinity*infinity)#inf print(ninfinity+infinity)#not a number print(1/-infinity)#is -0.0 print(nan*nan)# is not a number print(1/infinity) # is 0.0 since 1/∞ is 0 

Output:

$ python3 floating.py inf nan -0.0 nan 0.0 

Comments

0

In Summary, there is two kinds definition for Infinity.

For Positive Infinity

posVal1 = math.inf posVal2 = float("inf") 

For Negative Infinity

negVal1 = -math.inf negVal2 = float("-inf") 

Comments

0

Use:

float('inf') 

Or the math module:

import math math.inf 

But if you print it, they will both return inf, which proves that math uses float('inf') as well.

Comments

0

For anyone who needs to define his own concept of a number, you could create your own class:

class Infinity(object): # equivalence def __eq__(self, other): return False # negation def __ne__(self, other): return False # less than def __lt__(self, other): return False # less than or equal def __le__(self, other): return False # greater than def __gt__(self, other): return False # greater than or equal def __ge__(self, other): return False 

Usage:

 y = Infinity() x = -99999999999999999999 print(y > x) # False print(y < x) # False 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.