Infinity in Python

KoshurAI
1 min readDec 31, 2022

--

In Python, the value float("inf") represents positive infinity, and float("-inf") represents negative infinity.

You can use the math.isinf() function from the math module to check if a float value is positive or negative infinity. For example:

import math

x = float("inf")
y = float("-inf")

print(math.isinf(x)) # True
print(math.isinf(y)) # True
print(math.isinf(0)) # False

Note that you cannot use the float type to represent infinity in all operations. For example, you cannot use it in comparisons or arithmetic operations. For example:

x = float("inf")
y = 1

print(x > y) # True
print(x + y) # inf
print(x - y) # inf
print(x * y) # inf
print(x / y) # inf

If you need to perform arithmetic operations with infinity, you can use the float("inf") and float("-inf") values as sentinel values to represent infinity in your code. However, keep in mind that these values are not equal to each other, so you should use the math.isinf() function to check for infinity rather than using the == operator.

--

--

KoshurAI
KoshurAI

Written by KoshurAI

Passionate about Data Science? I offer personalized data science training and mentorship. Join my course today to unlock your true potential in Data Science.

No responses yet