Floating-point accuracy and missing values
2.5.5
Choose tolerances, identify finite values, and keep track of excluded data.
On this page
Compare using a tolerance
Binary floating-point arithmetic can produce small rounding differences. isclose combines a relative tolerance based on the reference value and an absolute tolerance. Set the tolerances according to the scale and meaning of the numbers.
import numpy as np
print(np.isclose(0.1 + 0.2, 0.3, rtol=0, atol=1e-12))
print(np.isclose(0.02, 0.0, rtol=0, atol=0.01))
Example output
True False
Distinguish NaN and infinity
isfinite excludes both NaN and positive or negative infinity. nanmean ignores NaN but can still include infinity. Choose a rule for invalid measurements and report how many observations each calculation actually used.
import numpy as np
a = np.array([2.0, np.nan, np.inf, 6.0])
valid = a[np.isfinite(a)]
print(valid.size, float(valid.mean()))
Example output
2 4.0