How do ufuncs work with NumPy's broadcasting rules?
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
How do NumPy universal functions (ufuncs) work with NumPy's broadcasting rules?
Ufuncs are functions such as `np.add`, `np.multiply` and `np.exp`, and the arithmetic operators on arrays call them. Explain what happens when their inputs have different shapes.
```hint Work one case
Write down the shapes of a `(3,)` array and a `(3, 1)` array, line them up from the right, and work out the shape of their sum.
```
```hint Memory
Think about how NumPy could treat a length-1 axis as if it were long without copying any data. Strides are the place to look.
```
### What a Strong Answer Covers
- What a ufunc does per element and at what point broadcasting happens
- The broadcasting rules: alignment from the trailing dimension, when two dimensions are compatible, and the result shape
- How the stretch happens without copying data
- Ufunc arguments and methods that interact with broadcasting, such as `out=`, `where=` and `outer`
- Failure cases and costs: incompatible shapes, silently wrong results, and large outputs
### Follow-up Questions
- `X` has shape `(n, d)`. Why is `X - X.mean(axis=1)` wrong, and when does it run without an error?
- How does `np.multiply.outer(a, b)` relate to `a[:, None] * b`?
- What do output elements contain where the `where=` mask is False and no `out=` array was passed?
- How do generalized ufuncs such as `np.matmul` broadcast when some dimensions are core dimensions?
Overview: Asks how NumPy universal functions such as np.add and np.exp combine arrays of different shapes through broadcasting. Tests the broadcasting rules, how size-1 axes are handled in memory, the out and where arguments, and the shape bugs that broadcasting can hide.