pytutorial/numpy/broadcasting
David Rotermund 74483bf356
Update README.md
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com>
2023-12-27 16:24:00 +01:00
..
broadcasting_1.png Add files via upload 2023-12-27 16:16:43 +01:00
broadcasting_2.png Add files via upload 2023-12-27 16:16:43 +01:00
broadcasting_3.png Add files via upload 2023-12-27 16:16:43 +01:00
broadcasting_4.png Add files via upload 2023-12-27 16:16:43 +01:00
README.md Update README.md 2023-12-27 16:24:00 +01:00

Broadcasting

{:.no_toc}

* TOC {:toc}

The goal

Broadcasting: Automatic adaption of dimensions

Questions to David Rotermund

General broadcasting rules

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimension and works its way left. Two dimensions are compatible when

  • they are equal, or
  • one of them is 1.

If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes.

Input arrays do not need to have the same number of dimensions. The resulting array will have the same number of dimensions as the input array with the greatest number of dimensions, where the size of each dimension is the largest size of the corresponding dimension among the input arrays. Note that missing dimensions are assumed to have size one.

broadcasting_1.png

Figure 1 (from numpy.org) : In the simplest example of broadcasting, the scalar b is stretched to become an array of same shape as a so the shapes are compatible for element-by-element multiplication.

broadcasting_2.png

Figure 2 (from numpy.org) : A one dimensional array added to a two dimensional array results in broadcasting if number of 1-d array elements matches the number of 2-d array columns.

broadcasting_3.png

Figure 3 (from numpy.org) : When the trailing dimensions of the arrays are unequal, broadcasting fails because it is impossible to align the values in the rows of the 1st array with the elements of the 2nd arrays for element-by-element addition.

broadcasting_4.png

Figure 4 (from numpy.org) : In some cases, broadcasting stretches both arrays to form an output array larger than either of the initial arrays.