You may see float(“inf”) or float(“-inf”) in some python codes. What does it mean? In this tutorial, we will use some examples to help you understand it.
Python float(‘inf’)
float(“inf”) represents a positive infinite number.
x = float("inf") print(x)
Here x will be inf.
Python float(‘-inf’)
float(“-inf”) represents a negative infinite number.
x = float("-inf") print(x)
Here x is -inf
We should notice: float(“inf”) = – float(“-inf”)
x = -float("-inf") == float("inf") print(x) # x = True
float(“inf”) operation
Here are some operations you should notice:
x = float("inf") print(x + 1) # x = inf print(x - 1) # x = inf print(x * 1) # x = inf print(x / 1) # x = inf
Here you can replace 1 with any scalar except 0 when calculating inf / 0.
x = float("inf") print(x + x) # x = inf print(x - x) # x = nan print(x * x) # x = inf print(x / x) # x = nan
From the result, we can find:
inf + inf = inf, however, inf-inf = nan
inf*inf=inf, however, inf/inf = nan
x = float("inf") print(x > 0) print(-x >0)
Run this code, we will get:
True False
It means we can use inf for a condition to get some value we wanted.