Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
python
broadcasting
communitycreator

What is the broadcast function in NumPy?

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The broadcast() function in NumPy's Python library is used to create an object that mimics broadcasting.

Broadcasting in NumPy describes how NumPy treats arrays with different shapes by making use of arithmetic operations. To know more about broadcasting in NumPy, see this shot.

Syntax

numpy.broadcast(in1, in2, ...)

Parameter value

The broadcast() function takes the parameter values, in1 in2 ..., which represents the input arrays.

Return value

The broadcast() function broadcasts the input arrays against each other and returns an object encapsulating the result.

Example

import numpy as np
# creating the input arrays
a = np.array([[1], [2], [3], [4]])
b = np.array([5, 6, 7, 8])

#  calling the broadcast() function 
np.broadcast(a,b)

# adding the two arrays using broadcasting
print(a + b)
Implementing the broadcast() function

Code explanation

  • Line 1: We import the numpymodule.
  • Line 3: We create an array a using the array() function.
  • Line 4: We create an array b using the array() function.
  • Line 7: We call the broadcast() function.
  • Line 10: We manually add the two arrays, a and b, using broadcasting. We print the result to the console.

RELATED TAGS

numpy
python
broadcasting
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring