5.6. Infinity and Not-A-Number (nan)#
Some arithmetic operations, such as division by zero, lead to infinity or undertermined numbers, which normally result in an error:
1 / 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[2], line 1
----> 1 1 / 0
ZeroDivisionError: division by zero
Since operations on arrays perform many arithmetic operations at once, it would be inconvenient to get an error each time only a few calculations fail. For this reason, instead of generating errors, NumPy only warns and provides special constants to express infinity (np.inf) and undetermined numbers (np.nan, not-a-number):
import numpy as np
a = np.array([0.0, 1.0, -1.0, 1.0])
b = np.array([0.0, 0.0, 0.0, 1.0])
c = a / b
c
/var/folders/7v/g5_ntzfx35v4ck07wflynw640000gp/T/ipykernel_69520/2090094188.py:6: RuntimeWarning: divide by zero encountered in divide
c = a / b
/var/folders/7v/g5_ntzfx35v4ck07wflynw640000gp/T/ipykernel_69520/2090094188.py:6: RuntimeWarning: invalid value encountered in divide
c = a / b
array([ nan, inf, -inf, 1.])
To know which operations resulted in nan or inf, use np.isnan and np.isinf:
np.isnan(c)
array([ True, False, False, False])
np.isinf(c)
array([False, True, True, False])
Good practice: Missing data
It is common in data analysis to use np.nan for representing missing data. For instance, we could record the (x, y, z) trajectory of a reflective marker and use (nan, nan, nan) when the marker is not seen by the cameras.