• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:17 mins read
You are currently viewing Python NumPy divide() Function

In NumPy, the numpy.divide() function is used to divide the elements of one array by the elements of another array. It performs element-wise division, broadcasting the arrays if necessary. This function provides several parameters that allow the user to specify what value to divide with. Use numpy.divide() function to divide the first array elements (arr) with the second array elements (arr1). Both arr and arr1 must have the same shape and the element in arr2 must not be zero; otherwise, it will raise an error. In this article, I will explain how to use the NumPy divide() function with examples.

1. Quick Examples of NumPy divide() Function

If you are in a hurry, below are some quick examples of how to use Python NumPy divide() function.


# Quick examples of numpy divide() function

# Example 1: Using divide() function
# Get division values 
arr = np.array([8, 27, 15, 18, 22, 34])
arr2 = np.divide(arr,4)

# Example 2: Use numpy.divide() 
# Divide numpy array elementwise
arr = [16, 28, 33, 38, 45]
arr1 = [4, 8, 13, 5, 3]
arr2 = np.divide(arr, arr1)

# Example 3: Divide arrays using / operator
arr = np.array([16, 28, 33, 38, 45])
arr1 = np.array([4, 8, 13, 5, 3])
arr2 = arr/arr1

# Example 4: Get division values
# Between two multi-dimensional arrays
arr = [[15, 23, 32], [9, -17, 25]]
arr1 = [[3, 5, 8], [-2, 4, 7]]
arr2 = np.divide(arr, arr1) 

# Example 5: Divide the array values by zero
arr = [16, 28, 33, 38, 45]
arr1 = [4, 8, 0, 5, 0]
arr2 = np.divide(arr, arr1) 

2. Syntax of NumPy divide()

Following is the syntax of the numpy.divide() function.


#  Syntax of numpy.divide() 
numpy.divide(arr1, arr2, out=None, where=True, casting='same_kind', order='K', dtype=None) 

2.1 Parameters of divide()

Following are the parameters of the divide() function.

  • arr1 The first input array or object works as a dividend.
  • arr2 – Second input array or object which works as a divisor.
  • out – It is ndarray, None, or tuple of ndarray and None, optional. Out will be the location where the result is to be stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly allocated array is returned.
  • where – This condition is broadcast over the input. True value means to calculate the unfunc at that position, whereas if the False value means to leave the value in output only.
  • casting (optional) – Controls what kind of data casting may occur during the operation. The default is ‘same_kind’.

2.2 Return Value of NumPy divide()

It returns an array that contains the division values of an input array.

3. Usage of NumPy divide() Function

The numpy.divide() function is used to perform element-wise division between two arrays or between an array and a scalar (numeric value). Returns a true division of the inputs, element-wise.

4 Divide NumPy Array by scalar (Single Value)

You can use the numpy.divide() function to divide a NumPy array by a scalar (single value). For instance, each element in the array arr is divided by the scalar value 4. The result is a new NumPy array with the element-wise division.


# Import numpy
import numpy as np
                 
# Create a 1D array
arr = np.array([8, 27, 15, 18, 22, 34])
print("Original 1D array:\n",arr)

# Using divide() function
# Get division values 
arr2 = np.divide(arr,4)
print("After getting division values:\n",arr2)

Yields below output.

numpy divide

5. Divide NumPy Array Elementwise

If you have two NumPy arrays and you want to perform element-wise division, you can use the numpy.divide() function. For example, the numpy.divide() function is used to perform element-wise division between the corresponding elements of arr and arr1. The result is a new NumPy array with the element-wise division values.


# Creating two input array
arr = np.array([16, 28, 33, 38, 45])
print("First array:",arr)
arr1 =np.array([4, 8, 13, 5, 3])
print("Second array:",arr1)

# Use numpy.divide() 
# Divide numpy array elementwise
arr2 = np.divide(arr, arr1)
print("Result after element-wise division:\n",arr2)

Yields below output.

numpy divide

6. Divide NumPy Arrays With the / Operator

You can use the division operator (/) directly for element-wise division of NumPy arrays. For example, the division operator (/) performs element-wise division between the corresponding elements of the two NumPy arrays, producing a new array with the division results.


# Creating two input array
arr = np.array([16, 28, 33, 38, 45])
print("First array:",arr)
arr1 =np.array([4, 8, 13, 5, 3])
print("Second array:",arr1)

# Use numpy.divide() 
# Use the division operator for element-wise division
arr2 = arr / arr1
print("Result after element-wise division using / operator:\n",arr2)

# Output:
# First array: [16 28 33 38 45]
# Second array: [ 4  8 13  5  3]
# Result after element-wise division using / operator:
#  [ 4.          3.5         2.53846154  7.6        15.        ]

7. Divide NumPy Two Multi-Dimensional Arrays

When you have two multi-dimensional NumPy arrays and you want to perform element-wise division, you can use the division operator (/) or the numpy.divide() function.

In the below example, both the division operator (/) and the numpy.divide() function performs element-wise division between the corresponding elements of the two multi-dimensional arrays, producing new arrays with the division results.


# Creating two multi-dimensional array
arr = np.array([[15, 23, 32], [9, -17, 25]])
arr1 = np.array([[3, 5, 8], [-2, 4, 7]])

# Using the division operator 
# For element-wise division
arr2 = arr / arr1
print("Result using / operator:\n",arr2)

# Using numpy.divide() for element-wise division
arr2 = np.divide(arr, arr1)
print("Result using numpy.divide():\n",arr2)

# Output:
# Result using / operator:
#  [[ 5.          4.6         4.        ]
#  [-4.5        -4.25        3.57142857]]

8. Divide NumPy Array by Using 0

Alternatively, element-wise division of the array arr by the array arr1 using numpy.divide(). However, you have some zeros in the divisor (arr1), which can lead to division by zero issues and result in inf or nan values.

As I mentioned above, the divisor array must not be zero otherwise it will raise an error. In this example, I have declared some of the divisor array elements are zero. Let’s see what happens.


# Creating two multi-dimensional array
arr = np.array([16, 28, 33, 38, 45])
arr1 = np.array([4, 8, 0, 5, 0])

# Use numpy division 
arr2 = np.divide(arr, arr1) 
print("After getting division values:\n",arr2)

# Output:
# RuntimeWarning: divide by zero encountered in true_divide
# [4.  3.5 inf 7.6 inf]

As you can see, division by zero results in inf values in the output array. It’s essential to handle such cases in your code to avoid unexpected results

Frequently Asked Questions

What is the purpose of the numpy.divide() function in NumPy?

The numpy.divide() function in NumPy is used for element-wise division of two arrays. It performs division on corresponding elements of two input arrays and returns a new array with the result. This operation is often useful in mathematical and scientific computations.

How does broadcasting work in the context of numpy.divide()?

Broadcasting is a NumPy feature that allows operations between arrays of different shapes and sizes. In the context of numpy.divide(), if the input arrays have different shapes, NumPy will automatically broadcast them to a common shape before performing the division.

Can the out parameter be used to perform in-place division?

The out parameter allows you to specify a location where the result should be stored. If provided, the result will be placed into the array specified by out. This can be useful for performing in-place division and saving memory by reusing an existing array.

How does the where parameter work in numpy.divide()?

The where parameter allows you to specify a condition. Only the elements corresponding to True values in the condition will be modified in the output array. This provides a way to selectively perform division based on a condition.

What precautions should be taken when using numpy.divide() to avoid division by zero?

Division by zero can lead to runtime warnings or errors. It’s important to handle cases where the denominator may be zero. You can use NumPy’s functions like numpy.where() or numpy.nan_to_num() to handle or replace such values and prevent issues related to division by zero.

Are there any considerations regarding data types and casting in numpy.divide()?

The casting parameter in numpy.divide() controls what kind of data casting may occur during the operation. The default value is ‘same_kind’, which means that the output will have the same data type as the inputs. Be aware of potential data type casting issues, especially when dealing with mixed data types in your arrays.

Conclusion

In this article, I have explained how to use numpy.divide() function syntax, parameters, and usage of how to calculate true division values of NumPy arrays with examples.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.