In all versions of Python, we can represent infinity and NaN (“not a number”) as follows:
pos_inf = float('inf') # positive infinity
neg_inf = float('-inf') # negative infinity
not_a_num = float('nan') # NaN ("not a number")
In Python 3.5 and higher, we can also use the defined constants math.inf
and math.nan
:
pos_inf = math.inf
neg_inf = -math.inf
not_a_num = math.nan
The string representations display as inf
and -inf
and nan
:
pos_inf, neg_inf, not_a_num
# Out: (inf, -inf, nan)
We can test for either positive or negative infinity with the isinf
method:
math.isinf(pos_inf)
# Out: True
math.isinf(neg_inf)
# Out: True
We can test specifically for positive infinity or for negative infinity by direct comparison:
pos_inf == float('inf') # or == math.inf in Python 3.5+
# Out: True
neg_inf == float('-inf') # or == -math.inf in Python 3.5+
# Out: True
neg_inf == pos_inf
# Out: False
Python 3.2 and higher also allows checking for finiteness:
math.isfinite(pos_inf)
# Out: False
math.isfinite(0.0)
# Out: True
Comparison operators work as expected for positive and negative infinity:
import sys
sys.float_info.max
# Out: 1.7976931348623157e+308 (this is system-dependent)
pos_inf > sys.float_info.max
# Out: True
neg_inf < -sys.float_info.max
# Out: True
But if an arithmetic expression produces a value larger than the maximum that can be represented as a float
, it will become infinity:
pos_inf == sys.float_info.max * 1.0000001
# Out: True
neg_inf == -sys.float_info.max * 1.0000001
# Out: True
However division by zero does not give a result of infinity (or negative infinity where appropriate), rather it raises a ZeroDivisionError
exception.
try:
x = 1.0 / 0.0
print(x)
except ZeroDivisionError:
print("Division by zero")
# Out: Division by zero
Arithmetic operations on infinity just give infinite results, or sometimes NaN:
-5.0 * pos_inf == neg_inf
# Out: True
-5.0 * neg_inf == pos_inf
# Out: True
pos_inf * neg_inf == neg_inf
# Out: True
0.0 * pos_inf
# Out: nan
0.0 * neg_inf
# Out: nan
pos_inf / pos_inf
# Out: nan