Other than the fact that math.inf
and -math.inf
were introduced in Python 3.5, there are no differences between them, and float('inf')
and float('-inf')
. They both follow the IEEE 754 floating-point standard and are equivalent representations of positive and negative infinity, respectively. Therefore, they can be used interchangeably. In fact, when you check the type of these values, you'll find that they are all of the same type:
import math print(type(math.inf)) # <class 'float'> print(type(float('inf'))) # <class 'float'> print(type(-math.inf)) # <class 'float'> print(type(float('-inf'))) # <class 'float'>
These representations can be used interchangeably in mathematical calculations, comparisons, and other operations. For instance, consider the following, where the math.isinf()
function can be seen to be compatible with both math.inf
and float('inf')
(and their negative counterparts):
import math print(math.isinf(math.inf)) # True print(math.isinf(-math.inf)) # True print(math.isinf(float('inf'))) # True print(math.isinf(float('-inf'))) # True print(math.isinf(42)) # False
Similarly, you can directly compare the values against either math.inf
or float('inf')
(and their negative equivalents):
import math print(math.inf == float('inf')) # True print(-math.inf == -float('inf')) # True
In the examples above, you can see that the values are equivalent to each other. The decision to choose one over the other typically depends on personal preference or the specific coding context. However, the math.inf
form is often preferred for semantics, readability and clarity.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.