5 ways to represent infinity in Python

5 ways to represent infinity in Python

Infinity is an undefined number in positive or negative. We often use infinity as placeholder or to compare numbers in various algorithms.

Here are the different ways we can represent infinity in Python

1. The simple float way

>>> a = float("inf")
>>> min(0, a)
0
>>> min(99999, a)
99999

Similarly here's negative infinity:

>>> b = float('-inf')
>>> b < 0
True
>>> b < -99999
True

2. using math module

>>> import math
>>> a = math.inf
>>> min(0, a)
0
>>> min(99999, a)
99999

and here's negative infinity

>>> b = -math.inf
>>> b < 0
True
>>> b < -99999
True

3. the numpy way

>>> import numpy
>>> a = numpy.inf
>>> a > 99999
True
>>> a > 0
True

4. Using decimal module

>>> from decimal import Decimal
>>> pos_inf = Decimal('Infinity')
>>> neg_inf = Decimal('-Infinity')
>>> Decimal('Infinity') == float('inf')
True
>>>
>>> pos_inf > 99999
True
>>> neg_inf < -99999
True

5. Using sympy module

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

Do you know more ways to represent infinite in Python? Share in comments.

That's it for now guys.

Happy coding, cheers! 🍻

 
Share this