Broadcasting is the mechanism that lets numpy-ts perform element-wise operations on arrays with different shapes without explicitly copying data. When you add a scalar to a matrix, or multiply a row vector by a column vector, broadcasting determines how the shapes align.numpy-ts follows NumPy’s broadcasting rules exactly.
Broadcasting compares shapes element-wise, starting from the trailing (rightmost) dimensions:
If the arrays have different numbers of dimensions, the shape of the smaller array is padded with 1s on the left until both shapes have the same length.
Arrays with size 1 along a particular dimension act as if they had the size of the array with the largest shape along that dimension. The element is repeated virtually (no memory copy).
If sizes disagree and neither is 1, broadcasting fails with an error.
When shapes are incompatible, numpy-ts throws an error. Two dimensions are incompatible when they differ and neither is 1:
Copy
Ask AI
const a = np.array([[1, 2, 3]]); // shape [1, 3]const b = np.array([[1, 2]]); // shape [1, 2]np.add(a, b);// Error: operands could not be broadcast together with shapes [1,3] [1,2]
When comparing shapes, numpy-ts right-aligns them and pads the shorter one with 1s on the left:
Copy
Ask AI
Example 1: [8, 1, 6, 1] and [7, 1, 5] 8 1 6 1 1 7 1 5 <- padded with 1 on the left => 8 7 6 5 <- take the max of each pairExample 2: [256, 256, 3] and [3] 256 256 3 3 <- padded to [1, 1, 3] 256 256 3 <- 1s stretch to matchExample 3: [15, 3, 5] and [15, 1, 5] 15 3 5 15 1 5 15 3 5 <- the 1 stretches to 3Example 4: [15, 3, 5] and [2, 5] INCOMPATIBLE 15 3 5 1 2 5 <- padded 15 ? 5 <- 3 vs 2, FAILS
Broadcasting only creates virtual copies. The element at the size-1 dimension is reused via stride tricks (stride of 0), so memory usage stays proportional to the original array, not the broadcast shape.