np.divide(a, b) always returns a floating-point result, even when dividing two integer arrays evenly, matching Python 3's own true-division behavior for /. Dividing by zero doesn't raise a Python exception the way plain Python division does — instead, NumPy emits a RuntimeWarning and fills the corresponding position with inf, for a nonzero numerator, or nan, for zero divided by zero, letting the rest of the array's computation continue rather than halting the whole operation.
1Understanding np.divide()
np.divide(a, b) always returns a floating-point result, even when dividing two integer arrays evenly, matching Python 3's own true-division behavior for /. Dividing by zero doesn't raise a Python exception the way plain Python division does — instead, NumPy emits a RuntimeWarning and fills the corresponding position with inf, for a nonzero numerator, or nan, for zero divided by zero, letting the rest of the array's computation continue rather than halting the whole operation.
Check for zero denominators explicitly before dividing, or use np.errstate() to control warning behavior, if inf/nan results from a division-by-zero would cause problems further down your computation.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([2, 5, 3])
print(np.divide(a, b))2Practical Example
Here is a real-world application of np.divide() showing how it is used in production NumPy code.
import numpy as np
a = np.array([1.0, 2.0, 0.0])
b = np.array([0.0, 4.0, 0.0])
result = np.divide(a, b)
print(result)3Best Practices
Follow these guidelines when working with np.divide():
1. Guard against zero denominators explicitly, or use np.where() to substitute a safe value, when division by zero is a realistic possibility
2. Use np.errstate(divide='ignore') deliberately, and briefly, when you intentionally expect and handle inf/nan results, to suppress the runtime warning noise
3. Prefer np.divide(a, b, out=..., where=condition) to skip computing division entirely for elements where it isn't valid or needed
Tip: Check for zero denominators explicitly before dividing, or use np.errstate() to control warning behavior, if inf/nan results from a division-by-zero would cause problems further down your computation.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([2, 5, 3])
print(np.divide(a, b))