NumPy divide()

The divide() function performs element-wise division of the elements in two arrays i.e., the elements of the numerator array are divided by the corresponding elements of the denominator array.

Example

import numpy as np

# create the numerator and denominator arrays
numerator = np.array([10, 20, 30])
denominator = np.array([2, 4, 5])

# perform element-wise division result = np.divide(numerator, denominator)
print(result) # Output: [ 5. 5. 6.]

divide() Syntax

The syntax of divide() is:

numpy.divide(array1, array2, out = None)

divide() Arguments

The divide() function takes following arguments:

  • array1 - the numerator array or scalar value
  • array2 - the denominator array or scalar value
  • out (optional) - the output array where the result will be stored

divide() Return Value

The divide() function returns an array that contains the result of element-wise division of the elements in two input arrays


Example 1: Use of divide() with scalar Denominator

import numpy as np

numerator = np.array([10, 20, 30])
denominator = 2

# perform element-wise division of numerator array by scalar denominator result = np.divide(numerator, denominator)
print(result)

Output

[ 5. 10. 15.]

Here, the np.divide() function is used to perform division of numerator by a scalar denominator value of 2.


Example 2: Divide NumPy Array by 0

import numpy as np

numerator = np.array([10, 20, 30])
denominator = np.array([2, 0, 10])

# perform element-wise division of the numerator array by the denominator array
result = np.divide(numerator, denominator)

print(result)

Output

[ 5. inf  3.]

Here, the division by zero in the second element of the denominator array results in inf, which indicates an infinite value.

Here, the second element of the resulting array is inf (which indicates infinite value) because we have divided 20 (in the numerator array) by 0 (in the denominator array).


Example: Use out to Store Output in Desired Location

import numpy as np

# create the numerator and denominator arrays
numerator = np.array([10, 20, 30])
denominator = np.array([2, 4, 5])

# create an empty array to store the divided values
result = np.empty_like(numerator, dtype=float)

# perform element-wise division
np.divide(numerator, denominator, out = result)

print(result)

Output

[5. 5. 6.]

Here, the divide() function is used with the out argument set to result. This ensures that the result of computing the division is stored in result.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges