Member-only story
Infinity in Python
2 min readFeb 5, 2025
In Python, you can represent infinity using float('inf')
. It can be used in mathematical operations, comparisons, and algorithms that require an infinitely large value.
Read for free: https://allwin-raju.medium.com/infinity-in-python-b1d8e03803aa?sk=b935756efd097f1f644f7064f7512494
Examples:
1. Positive and Negative Infinity
pos_inf = float('inf')
neg_inf = float('-inf')
print(pos_inf) # inf
print(neg_inf) # -inf
2. Comparison with Other Numbers
print(1000 < float('inf')) # True
print(-1000 > float('-inf')) # True
3. Arithmetic with Infinity
Python allows you to perform arithmetic operations with infinity. Here’s how it behaves in different cases:
print(float('inf') + 100) # inf
print(float('-inf') - 100) # -inf
print(float('inf') * 2) # inf
print(float('inf') / float('inf')) # nan (Not a Number)
4. Using math.inf
(Recommended)
Python’s math
module provides a more readable way:
import math
print(math.inf) # inf
print(-math.inf) # -inf