NumPy - Array Division



NumPy Array Division

NumPy array division refers to the process of dividing two arrays element-wise. In this context, element-wise division means that each element in one array is divided by the corresponding element in another array.

This operation supports broadcasting, allowing for division between arrays of different shapes. Additionally, division can be performed between an array and a scalar, which scales each element of the array accordingly.

Element-wise Division in NumPy

Element-wise division in NumPy refers to dividing each element of one array by the corresponding element in another array. This operation is performed element by element, meaning that the division occurs pairwise between the elements of the two arrays at the same positions.

For element-wise division to work, the two arrays must have the same shape, or they must be broadcastable to a common shape.

In NumPy, the division operator / is used to perform element-wise division. If the arrays have different shapes but are compatible for broadcasting, NumPy will automatically apply broadcasting rules to perform the division.

Example

In the following example, we are dividing each element of array a by the corresponding element of array b

import numpy as np

# Creating two arrays
a = np.array([10, 20, 30])
b = np.array([2, 5, 10])

# Performing element-wise division
result = a / b
print(result)

Following is the output obtained −

[5. 4. 3.]

Division by a Scalar in NumPy

Division by a scalar in NumPy refers to dividing each element of an array by a single scalar value. This operation applies the division to every element of the array, resulting in a new array where each element has been divided by the scalar.

Example

In this example, we are dividing each element of the array "a" with the scalar "10" −

import numpy as np

# Creating an array
a = np.array([10, 20, 30])

# Dividing by a scalar
result = a / 10
print(result)

This will produce the following result −

[1. 2. 3.]

Broadcasting in Array Division

Broadcasting allows for operations between arrays of different shapes. When performing division between arrays of different shapes, NumPy automatically adjusts the shapes so that the operation can be performed.

When performing array division, broadcasting allows you to divide arrays of different sizes or shapes by automatically expanding the smaller array along the missing dimensions to match the shape of the larger array.

This expansion is done in a way that allows element-wise operations, like division, to be performed without explicitly replicating the data.

Example

In the example below, array "b" is broadcasted to match the shape of array "a", and then element-wise division is performed −

import numpy as np

# Creating arrays with different shapes
a = np.array([[10, 20, 30], [40, 50, 60]])
b = np.array([10, 5, 2])

# Performing division with broadcasting
result = a / b
print(result)

Following is the output of the above code −

[[ 1.  4. 15.]
 [ 4. 10. 30.]]

Handling Division by Zero

When performing division operations in NumPy, one common issue is the possibility of dividing by zero, which can lead to undefined or infinite results. NumPy provides ways to handle such scenarios, either by returning special values (like inf or nan) or by raising warnings or errors depending on the specific use case.

  • Positive/Negative Infinity (inf or -inf) − It is returned when a positive or negative number is divided by zero.
  • Not a Number (nan) − It is returned when zero is divided by zero.

Example: Basic Division by Zero

Let us see how NumPy handles a simple division by zero −

import numpy as np

# Creating an array with a zero element
array = np.array([10, 0, -5])

# Dividing a constant by the array
result = 100 / array
print(result)

NumPy does not raise an error but instead returns "inf" for division by zero −

/home/cg/root/66c57b63ef7f5/main.py:7: RuntimeWarning: divide by zero encountered in divide
  result = 100 / array
[ 10.  inf -20.]

Example: Handling Division by Zero Using errstate() Function

You can control how NumPy handles division by zero using np.errstate() function. This function allows you to specify whether to ignore, warn, or raise an error for floating-point errors like division by zero −

import numpy as np

# Creating an array with a zero element
array = np.array([10, 0, -5])

with np.errstate(divide='ignore', invalid='ignore'):
   result = 100 / array
   print(result)

Here, we set the "divide" parameter to "ignore" in the errstate() function to ignore the warning that generally occurs with division by zero. The result still contains "inf", but without any interruption or warning −

/home/cg/root/66c57b63ef7f5/main.py:7: RuntimeWarning: divide by zero encountered in divide
  result = 100 / array
[ 10.  inf -20.]

Example: Handling nan Values

When zero is divided by zero, the result is nan (Not a Number). This special value is used to represent undefined or unrepresentable values in floating-point calculations −

import numpy as np

# Creating arrays with zero elements
numerator = np.array([0, 1, 2])
denominator = np.array([0, 0, 2])

# Performing division
result = numerator / denominator
print(result)

The result produced is as follows −

[ 10.  inf -20.]

Division with Different Data Types

When performing division between arrays of different data types, NumPy automatically promotes the data types to a common type that can safely contain the result.

For example, if you divide an integer array by a float array, the result will be a float array. This type promotion prevents data loss and ensures the precision of the results.

Example

In this example, NumPy promotes the integer array a to a float type to match the data type of array b before performing the division −

import numpy as np

# Creating arrays with different data types
a = np.array([10, 20, 30], dtype=np.int32)
b = np.array([2.5, 5.0, 10.0], dtype=np.float64)

# Performing division
result = a / b
print(result)

We get the output as shown below −

[4. 4. 3.]

Matrix Division in NumPy

Matrix division is not as straightforward as element-wise division or scalar division. However, you can solve for a matrix division-like operation by using matrix multiplication with the inverse of a matrix in NumPy.

Example

In this example, we use the inverse of matrix B to perform a division-like operation in NumPy −

import numpy as np

# Creating a matrix
A = np.array([[1, 2], [3, 4]])

# Creating another matrix
B = np.array([[2, 0], [1, 3]])

# Solving the matrix division A/B
# Equivalent to A * B^-1
result = np.dot(A, np.linalg.inv(B))
print(result)

Following is the output obtained −

[[0.16666667 0.66666667]
 [0.83333333 1.33333333]]

Handling Dimension Mismatch in Division

When performing division operations between arrays in NumPy, dimension mismatch can occur if the arrays do not share compatible shapes. NumPy addresses this issue through broadcasting and raises a ValueError in such case.

Example

In the following example, the shapes of "a" and "b" are not compatible for broadcasting, resulting in an error −

import numpy as np

# Creating arrays with incompatible shapes
a = np.array([1, 2, 3])
b = np.array([[1, 2], [3, 4]])

# Attempting to divide incompatible arrays
result = a / b
print(result)

The result produced is as follows −

Traceback (most recent call last):
File "/home/cg/root/66c57b63ef7f5/main.py", line 8, in <module>
   result = a / b
ValueError: operands could not be broadcast together with shapes (3,) (2,2) 
Advertisements