पाठ 5 / 25
Floating Point, Overflow and NaN
Numbers that surprise.
Know the limits of the types
Floating-point numbers are binary approximations: 0.1 + 0.2 != 0.3, and adding very large and very small numbers loses precision. Compare floats with np.isclose. Fixed-size integers wrap around on overflow (uint8 200 + 100 gives 44) without an error. Division by zero gives inf with a warning, and NaN (not a number) is not equal to itself and spreads through calculations unless you use nan-aware functions such as np.nanmean.
Precision, overflow and NaN behaviour, run
I ran this with Python 3.12.3 and NumPy 2.5.3. Each line shows a classic surprise. Warnings were silenced for the run; NumPy normally prints a RuntimeWarning for division by zero and the mean containing NaN.
import numpy as np
print(0.1 + 0.2 == 0.3)
print(np.isclose(0.1 + 0.2, 0.3))
a = np.array([1e16, 1.0, -1e16])
print(a.sum(), "vs exact 1.0")
print(np.array([200], dtype=np.uint8) + np.uint8(100))
print(np.array([1, 2, 3]) / 0)
print(np.nan == np.nan, np.isnan(np.nan))
print(np.mean([1.0, np.nan, 3.0]), np.nanmean([1.0, np.nan, 3.0]))
Output:
False True 0.0 vs exact 1.0 [44] [inf inf inf] False True nan 2.0
Use int64 and float64 by default
Choose smaller dtypes only for memory reasons and after checking that values fit.
त्वरित जाँच: What is np.mean([1.0, np.nan, 3.0])?
- 2.0
- nan
- 4.0
- An error
Answer
nan — NaN spreads; use np.nanmean to ignore it.