NumPy divide() in Python

Share this article

In Python, numpy.divide() is a function used to perform element-wise division of two arrays. It takes two arrays (or an array and a scalar) and divides each element in the first array by the corresponding element in the second array.

Key Takeaway

numpy.divide() allows you to divide each element in one array by the corresponding element in another array (or by a constant). This function is useful when you need to perform element-wise division efficiently in large datasets or matrices.

Example

import numpy as np

arr1 = np.array([10, 20, 30])
arr2 = np.array([2, 4, 5])

result = np.divide(arr1, arr2)
print(result)  # Output: [5. 5. 6.]

What it does

Here, numpy.divide() divides each element in arr1 by the corresponding element in arr2. The result is [10/2, 20/4, 30/5], which gives [5.0, 5.0, 6.0].

  • Element-wise: Each element in the first array is divided by the corresponding element in the second array.
  • Broadcasting: If one input is a scalar, it is broadcasted to divide all elements of the array.

Examples

Example 1: Dividing an array by a scalar

arr = np.array([8, 16, 24])
result = np.divide(arr, 4)
print(result)  

# Output: [2. 4. 6.]

This divides each element of arr by 4, resulting in [8/4, 16/4, 24/4], which gives [2.0, 4.0, 6.0].

Example 2: Division with multi-dimensional arrays

arr1 = np.array([[12, 18], [24, 30]])
arr2 = np.array([[3, 6], [8, 5]])

result = np.divide(arr1, arr2)
print(result)

# Output:
# [[4. 3.]
#  [3. 6.]]

In this example, numpy.divide() performs element-wise division for each corresponding pair of elements in the 2D arrays.

Example 3: Division by zero handling

arr1 = np.array([5, 10, 15])
arr2 = np.array([1, 0, 3])

result = np.divide(arr1, arr2)
print(result)  

# Output: [ 5. inf  5.]

When a division by zero occurs, NumPy returns inf (infinity) rather than raising an error. This can be useful when handling data that may contain zeros.

Example 4: Using out parameter

arr1 = np.array([10, 20, 30])
arr2 = np.array([2, 4, 5])
out_arr = np.zeros(3)

np.divide(arr1, arr2, out=out_arr)
print(out_arr)  

# Output: [5. 5. 6.]

Here, the out parameter is used to store the result in a pre-defined array (out_arr). This can help save memory, especially when working with large datasets.