Introduction to np.nan and np.inf in NumPy
NumPy provides special floating-point values: np.nan (Not a Number) and np.inf (Infinity) to handle undefined and infinite numerical operations.
1. Importing NumPy
Before using NumPy, it needs to be imported.
import numpy as np
2. Understanding np.nan (Not a Number)
np.nan represents an undefined or unrepresentable value, such as 0/0 or the result of an invalid mathematical operation.
a = np.nan
print(a) # Output: nan
print(np.isnan(a)) # Output: True
3. Operations Involving np.nan
Any arithmetic operation with np.nan results in np.nan.
print(np.nan + 5) # Output: nan
print(np.nan * 2) # Output: nan
print(np.nan == np.nan) # Output: False
4. Handling np.nan
To check for np.nan values in an array, use np.isnan(), and to replace them, use np.nan_to_num().
arr = np.array([1, 2, np.nan, 4])
print(np.isnan(arr)) # Output: [False False True False]
print(np.nan_to_num(arr)) # Output: [1. 2. 0. 4.]
5. Understanding np.inf (Infinity)
np.inf represents positive infinity, and -np.inf represents negative infinity.
inf_value = np.inf
neg_inf_value = -np.inf
print(inf_value) # Output: inf
print(neg_inf_value) # Output: -inf
6. Operations Involving np.inf
Arithmetic operations with np.inf follow mathematical rules of infinity.
print(np.inf + 100) # Output: inf
print(np.inf * 2) # Output: inf
print(np.inf / np.inf) # Output: nan
7. Handling np.inf
To check for infinite values in an array, use np.isinf().
arr = np.array([1, np.inf, -np.inf, 4])
print(np.isinf(arr)) # Output: [False True True False]
Conclusion
NumPy provides np.nan and np.inf to handle undefined and infinite numerical operations. Proper handling of these values ensures robust numerical computations.