Vectorized Math Operations, Universal Functions (ufuncs) & Broadcasting Rules
Overview & Learning Objectives
Vectorization is the practice of replacing explicit loops with array expressions that execute compiled C code. Universal functions (`ufuncs`) operate element-by-element across arrays. When arrays have different shapes, NumPy applies **Broadcasting Rules** to stretch matching dimensions without copying data, enabling seamless arithmetic between vectors and matrices.
- Perform element-wise arithmetic and mathematical operations using universal functions.
- Understand the 2 fundamental NumPy Broadcasting Rules.
- Multiply matrices and vectors without explicit Python for loops.
Industry Standard
Standard: Engineering practices at Uber require vectorizing all spatial distance and ETA calculations via NumPy broadcasting, reducing latency from 800ms in pure Python to under 4ms.
Real-World Example: ScoopCraft GST & Discount Calculator
ScoopCraft applies an array of store-specific discount percentages [0.10, 0.05, 0.15] across a matrix of product prices.
| Product Name | Base Price (₹) | Store A (-10%) | Store B (-5%) | Store C (-15%) |
|---|---|---|---|---|
| Belgian Choco Tub | 350.00 | 315.00 | 332.50 | 297.50 |
| Almond Crunch Tub | 300.00 | 270.00 | 285.00 | 255.00 |
| Mango Delight Tub | 250.00 | 225.00 | 237.50 | 212.50 |
| Kesar Pista Cup | 120.00 | 108.00 | 114.00 | 102.00 |
Syntax & Core Code Implementation
import numpy as np
# Prices vector: shape (4, 1) -> 4 rows, 1 col
prices = np.array([[350.0], [300.0], [250.0], [120.0]])
# Discount rates vector: shape (1, 3) -> 1 row, 3 stores
discounts = np.array([[0.10, 0.05, 0.15]])
# Broadcasting stretches shapes: (4, 1) * (1, 3) -> (4, 3) matrix!
final_prices = prices * (1.0 - discounts)
# Mathematical ufuncs
log_prices = np.log(prices)
sqrt_prices = np.sqrt(prices)
rounded_bills = np.round(final_prices, 2)
Parameters & Arguments Breakdown
Broadcasting Rule 1: If arrays have different number of dimensions, pad shape of smaller array on the LEFT with 1s until dimensions match.Broadcasting Rule 2: Two dimensions are compatible if they are EQUAL, or if one of them is 1. If 1, it stretches along that axis.ufunc: Universal function implementing fast element-wise operations with support for broadcasting, type casting, and reduction.
Sample Walkthrough (Q&A)
Question: Can an array of shape `(4, 3)` broadcast with an array of shape `(4,)`?
Code Pattern: (4, 3) + (4,)
Result: ValueError: operands could not be broadcast together with shapes (4,3) (4,)
Explanation: Per Rule 1, `(4,)` becomes `(1, 4)`. Comparing `(4, 3)` with `(1, 4)`: trailing dimensions 3 and 4 are neither equal nor is one of them 1! To fix, reshape `(4,)` to `(4, 1)`.
Common Mistakes & Limitations
- Attempting to broadcast arrays with incompatible trailing dimensions without reshaping (`arr[:, np.newaxis]`).
- Using Python math functions (`import math; math.sqrt(arr)`) which fail on arrays; always use `np.sqrt(arr)`.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Insert New Axis for Broadcasting | arr[:, np.newaxis] | arr[:, np.newaxis] |
| Fast Matrix Multiplication | A @ B | A @ B |
Pro Tips & Modern Best Practices
- Use `np.einsum()` (Einstein summation convention) for complex multi-dimensional tensor contractions and dot products.
- Use Numba (`@numba.jit`) to compile custom non-vectorizable loops directly to native machine instructions.