To use infinity in Python and create variables which represent infinity, there are four different ways.
The easiest way to get infinity in Python is with the float() function.
infinity = float('inf')
print(infinity)
#Output:
inf
Another way you can represent infinity in Python is with the math module.
import math
infinity = math.inf
print(infinity)
#Output:
inf
Another way you can represent infinity in Python is with the decimal module.
import decimal
infinity = decimal.Decimal("inf")
print(infinity)
#Output:
inf
One final way to represent infinity is with the numpy module.
import numpy as np
infinity = np.inf
print(infinity)
#Output:
inf
Each of these methods create variables which are equal to infinity and they are all have the same representations in Python.
import math
import decimal
import numpy as np
print(float('inf') == math.inf == decimal.Decimal('inf') == np.inf)
#Output:
True
How to Use Infinity in Python
After you’ve initialized a variable and assigned it a value of infinity with one of the four methods shown above, you can use infinity just like any other number in Python.
For example, you can perform any of the basic arithmetic operations such as addition, subtraction, division or multiplication.
You can also do things such as comparing infinity with other numbers or finding the maximum or minimum of numbers including infinity.
infinity = float('inf')
print(infinity + 100)
print(infinity - 100)
print(infinity * 100)
print(100 / infinity)
print(max(infinity, 100))
print(min(infinity, 100))
#Output:
inf
inf
inf
0.0
inf
100
Using Negative Infinity in Python
If you want to use negative infinity in Python, then you can multiply any of the above variables by -1 and get negative infinity.
For example, if you want to use the float() function to create infinity, then just multiply the returned value by -1 and you’ll get negative infinity.
Below shows a simple example of how you can get negative infinity in Python.
negative_infinity = -float('inf')
print(negative_infinity)
#Output:
-inf
Then after you’ve created a variable representing negative infinity, you can use it just like positive infinity.
Hopefully this article has helped you understand how to create variables representing infinity in Python.