Broadcasting with NumPy Arrays

Introduction to Broadcasting with NumPy Arrays

The word broadcasting refers to how Numpy handles arrays of differing dimensions during arithmetic operations that result in constraints. The smaller array is broadcast over the bigger array so that their shapes are compatible.

Broadcasting allows for the vectorization of array operations, allowing looping to take place in C rather than Python, as Numpy does. It accomplishes this without duplicating data, resulting in fast algorithm implementations. In certain circumstances, broadcasting is a negative idea since it results in wasteful memory usage, which slows down processing.

Algorithm of Broadcasting with NumPy Arrays

Inputs: Array A with m dimensions and array B with n dimensions.

p = max(m, n)
if m < p:
    left-pad A's shape with 1s until it also has p dimensions

else if n < p:
    left-pad B's shape with 1s until it also has p dimensions
result_dims = new list with p elements

for i in p-1 ... 0:
    A_dim_i = A.shape[i]
    B_dim_i = B.shape[i]
    if A_dim_i != 1 and B_dim_i != 1 and A_dim_i != B_dim_i:
        raise ValueError("could not broadcast")
        # Pick the Array which is having maximum Dimension
        result_dims[i] = max(A_dim_i, B_dim_i) 

Broadcasting Rules:

The following rules apply when broadcasting two arrays together:

  1. If the arrays are not of the same rank, add 1s to the lower rank array’s form until both shapes are the same length.
  2. In a dimension, two arrays are compatible if they have the same size in that dimension or if one of the arrays has size 1.
  3. If the arrays are compatible in all dimensions, they can be broadcast jointly.
  4. Following broadcasting, each array acts as if its shape were equal to the element-wise maximum of the two input arrays’ forms.
  5. The first array acts as if it were copied along any dimension where one array has a size 1 and the other array has a size larger than 1.

Code Examples

Example 01: Single dimension array

# welcome to
import numpy as np
a = np.array([34, 23, 12]) # 1x3 Dimension array
b = 5

# Broadcasting happened because of
# miss match in array Dimension.
c = a + b


[34 23 12]
[39 28 17]

Example 02: Two dimension array

# welcome to
import numpy as np
A = np.array([[4, 23, 65], [54, 32, 22]])

b = 5

C = A + b


[[ 4 23 65]
 [54 32 22]]
[[ 9 28 70]
 [59 37 27]]

Example 03:

# welcome to
import numpy as np

v = np.array([23, 3, 43])
w = np.array([15, 5])

# To compute an outer product we first
# reshape v to a column vector of shape 3x1
# then broadcast it against w to yield an output
# of shape 3x2 which is the outer product of v and w
print(np.reshape(v, (3, 1)) * w, "\n")

X = np.array([[42, 3, 21], [5, 32, 32]])

# x has shape 2x3 and v has shape (3, )
# so they broadcast to 2x3,
print(X + v, "\n")

# Add a vector to each column of a matrix X has
# shape 2x3 and w has shape (2, ) If we transpose X
# then it has shape 3x2 and can be broadcast against w
# to yield a result of shape 3x2.

# Transposing this yields the final result
# of shape 2x3 which is the matrix.
print((X.T + w).T, "\n")

# Another solution is to reshape w to be a column
# vector of shape 2X1 we can then broadcast it
# directly against X to produce the same output.
print(X + np.reshape(w, (2, 1)), "\n")

# Multiply a matrix by a constant, X has shape 2x3.
# Numpy treats scalars as arrays of shape();
# these can be broadcast together to shape 2x3.
print(X * 2)


[[345 115]
 [ 45  15]
 [645 215]] 

[[65  6 64]
 [28 35 75]] 

[[57 18 36]
 [10 37 37]] 

[[57 18 36]
 [10 37 37]] 

[[84  6 42]
 [10 64 64]]

Example 04: Plotting a two-dimensional function

Images based on two-dimensional functions are regularly display via broadcasting. If we wish to define a function, we may use the formula z=f (x, y).

# welcome to
import numpy as np
import matplotlib.pyplot as plt

# Computes x and y coordinates for
# points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])


plotting two dimensional function


What is the benefit of broadcasting across Numpy’s arrays?

By effectively reproducing the smaller array along the last mismatched dimension, broadcasting overcomes the problem of arithmetic between arrays of different forms. Numpy’s treatment of arrays of diverse forms during arithmetic operations is refer to as broadcasting.

How do I broadcast an array in NumPy?

NumPy’s ability to treat arrays of various forms during arithmetic operations is refer to as broadcasting. Arithmetic operations on arrays are normally perform on the items that correspond to each other. These procedures are execute smoothly if two arrays have the exact same shape.


That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.atleast_3d() – The NumPy atleast_3d Python Function

Leave a Comment