Special Floats#

NumPy does not raise an exception if we use mathematical operations which lead to undefined results. Instead, NumPy prints a warning and returns one of several special floating point numbers.

import numpy as np

Infinity#

Results of some undefined operations can be interpreted as plus or minus infinity. NumPy represents infinity by the special float np.inf:

a = np.array([1, -1])
b = a / 0

print(b)
print(type(b[0]))
[ inf -inf]
<class 'numpy.float64'>
/tmp/ipykernel_69952/2743290674.py:2: RuntimeWarning: divide by zero encountered in true_divide
  b = a / 0

If there is some good reason we may also use np.inf in assignments:

a = np.inf

print(a)
inf

Also well defined operations may lead to infinity if the range of floats is exhausted:

print(np.array([1.23]) ** 10000)
[inf]
/tmp/ipykernel_69952/1071891269.py:1: RuntimeWarning: overflow encountered in power
  print(np.array([1.23]) ** 10000)

Calculations with np.inf behave as expected:

print(np.inf + 1)
print(5 * np.inf)
print(0 * np.inf)
print(np.inf - np.inf)
inf
inf
nan
nan

Not a Number#

Results of undefined operations which cannot be interpreted as infinity are represented by the special float np.nan (not a number).

a = np.array([-1, 1])
b = np.log(a)

print(b)
[nan  0.]
/tmp/ipykernel_69952/3972426452.py:2: RuntimeWarning: invalid value encountered in log
  b = np.log(a)

Calculations with np.nan always lead to np.nan:

print(np.nan + 1)
print(5 * np.nan)
print(0 * np.nan)
nan
nan
nan

Comparison of and to Special Floats#

Don’t use usual comparison operators for testing for special floats. They show strange (but well-defined) behavior:

print(np.nan == np.nan)
print(np.inf == np.inf)
False
True

Instead, call np.isnan or np.isposinf (for \(+\infty\)) or np.isneginf (for \(-\infty\)) or np.isinf (for both).

Comparisons between finite numbers and np.inf are okay:

print(5 < np.inf)
True

NumPy Functions Handling np.nan#

Some NumPy function come in two variants, which differ in handling np.nan. Look at amin and nanmin, for instance.