NumPy Broadcasting - NumPy

What is Broadcasting in NumPy?

During arithmetic operations, NumPy facilitates to treat arrays of different shapes. This ability of NumPy is referred to as broadcasting. The arithmetic operations are usually performed on the corresponding elements. The operations are smoothly performed for the arrays which are usually of the same shape.

Example 1

The output appears as:

The element-to-element operations are not possible for the arrays with dissimilar dimensions. The operations are possible by NumPy as it provides with the broadcasting feature. When some of the rules are satisfied, broadcast facility is possible such as:

• Array with smaller ndim than the other is prepended with '1' in its shape.
• Size in each dimension of the output shape is maximum of the input sizes in that dimension.
• An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1.
• If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

When the above mentioned rules produce a valid result broadcasting is possible for the set of arrays and should be true for the following:

• Arrays have exactly the same shape.
• Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.
• Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.

Broadcasting is illustrated below:

Example 2

The output appears as:

The pictorial representation of broadcasting array b to make it compatible with array a is as follows: NumPy Topics