Broadcasting & ufuncs

  • Learn NumPy broadcasting and ufuncs to perform operations efficiently on arrays of different shapes.
  • Broadcasting Rules

    What is Broadcasting?

    Broadcasting is a mechanism that allows NumPy to perform operations on arrays of different shapes without explicitly reshaping them.

    Instead of copying data, NumPy virtually expands smaller arrays to match larger ones during operations.

    Why Broadcasting is Needed

    • Perform operations between arrays of different sizes

    • Avoid writing extra code for reshaping

    • Improve performance and memory usage

    Example – Simple Broadcasting

import numpy as np

arr = np.array([10, 20, 30])
result = arr + 5

print(result)
  • Output:

[15 25 35]
  • Here, the scalar 5 is broadcast to match the array shape.

    Broadcasting Rules

    NumPy compares array shapes from right to left:

    1. Dimensions are compatible if:

      • They are equal, or

      • One of them is 1

    2. Missing dimensions are treated as 1

    3. If dimensions are incompatible → error

    Example – Broadcasting 2D with 1D

matrix = np.array([[1, 2, 3],
                   [4, 5, 6]])

vector = np.array([10, 20, 30])

print(matrix + vector)
  • Each row of the matrix adds the vector automatically.

    Broadcasting Flow (Concept)

    Smaller Array → Expanded Virtually → Operation Applied → Result Array

    ❌ Broadcasting Error Example

a = np.array([1, 2, 3])
b = np.array([1, 2])

print(a + b)  # Error: incompatible shapes
  • Universal Functions (ufuncs)

    What are ufuncs?

    Universal Functions (ufuncs) are fast, vectorized functions that operate element-wise on NumPy arrays.

    They are implemented in C and optimized for performance.

    Categories of ufuncs

    Arithmetic ufuncs

np.add(a, b)
np.subtract(a, b)
np.multiply(a, b)
np.divide(a, b)
  • Mathematical ufuncs

np.sqrt(arr)
np.square(arr)
np.log(arr)
np.exp(arr)
  • Trigonometric ufuncs

np.sin(arr)
np.cos(arr)
np.tan(arr)
  • Comparison ufuncs

np.greater(arr, 20)
np.less(arr, 50)
np.equal(arr, 30)
  • Example – ufunc in Action

values = np.array([1, 4, 9, 16])

print(np.sqrt(values))
  • Combining Broadcasting & ufuncs

data = np.array([10, 20, 30])
scaled = np.multiply(data, 1.5)

print(scaled)