- Published on
What is `inf` in Python?
- Authors
- Name
- hwahyeon
When solving coding tests or similar tasks in Python, there are times when you need to assign a very large value to a variable meant to store the minimum value. In such cases, using inf
ensures that any number compared to it will always be smaller.
min_val = float('inf')
print(min_val > 10000000000) # True
print(min_val > -100) # True
Similarly, for negative values, you can use -inf
to set the smallest possible value.
max_val = float('-inf')
print(max_val < -10000000000) # True
print(max_val < 100) # True
You don't have to use only float('inf')
, you can also use math.inf
. Both methods represent infinity and can be chosen based on your coding style or whether you're using the math
module.
import math
min_val = math.inf
print(min_val > 10000000000) # True
The principle of inf
is based on the IEEE 754 standard. Python's float
follows this standard for floating-point numbers. According to this standard, certain bit patterns are designated to represent special values such as "infinity."
When you use float('inf')
or math.inf
, Python stores this as a floating-point value that it interprets as infinity. These values are designed to always be greater than any other number (or smaller in the case of -inf
).