---
title: "Lab: multivariable functions in code"
heading: Gradients, tolerances and optimization by computer
eyebrow: A9 · Lesson 7 · Lab: multivariable functions
xp: 60
---

::: hook
Lessons 4 to 6 took derivatives of functions of several variables by hand. In practice those functions are often a simulation or a measurement, with no formula to differentiate. In this lab you'll compute gradients numerically, compare three ways of estimating how component tolerances spread to a circuit's output, climb a power surface to the maximum-power load, fit a plane to sensor readings, and solve two nonlinear equations at once with Newton's method in two variables.
:::

::: play
- The surface is the power delivered to a load $R_L + jX_L$ by a 10 V source with impedance $50 + 30j$ Ω, shown as a slice through $X_L$.
- Move $X_L$: the peak over $R_L$ is highest when $X_L = -30$ Ω cancels the source's reactance.
- At that slice the peak sits at $R_L = 50$ Ω, the conjugate match, delivering 0.25 W.
:::

```sim plot
view: graph
x: RL = 1..200 Ω
y: P = 0..0.27 W
slider: XL = -100..50 step 1 = 0 Ω
plot: 0.5*100*RL/((50 + RL)^2 + (30 + XL)^2) | label: power into the load | samples: 600
readout: best R_L for this X_L, Ω = sqrt(50^2 + (30 + XL)^2) | digits: 4
readout: largest possible power, W = 0.25 | digits: 3
```

::: predict
## Two 10 kΩ resistors in a divider each vary independently with a standard deviation of 50 Ω. Compared with adding the two effects' sizes, the actual spread of the output is:

- [ ] The same
- [x] Smaller, by a factor of about $\sqrt2$
- [ ] Larger
- [ ] Zero, since the errors cancel

::: reveal
Smaller by about $\sqrt2$. Independent errors add in squares: the output's standard deviation is $\sqrt{(\partial_1\sigma_1)^2 + (\partial_2\sigma_2)^2}$, and with equal contributions that's $\sqrt2$ times one of them, not 2. Adding the sizes gives the worst case, which is real but rare. A Monte Carlo simulation of many random dividers confirms the root-sum-square figure.
:::
:::

::: nameit
## Numerical gradients

Central differences estimate each partial derivative:

$$\frac{\partial f}{\partial x} \approx \frac{f(x + h, y) - f(x - h, y)}{2h}$$

with error proportional to $h^2$; $h \approx 10^{-5}$ times the variable's size balances that against rounding.

## Three tolerance estimates

For an output $y = f(x_1, \ldots, x_n)$ with independent input errors $\sigma_i$:
- **worst case:** $\sum|\partial_if|\Delta x_i$, the largest possible deviation;
- **root-sum-square:** $\sqrt{\sum(\partial_if\,\sigma_i)^2}$, the standard deviation for small, independent errors;
- **Monte Carlo:** draw thousands of random input sets, compute $y$ for each, and measure its spread directly. It handles large errors and nonlinear functions where the linear estimates fail.

## Optimization and Newton's method

**Gradient ascent** steps uphill: $\mathbf x \leftarrow \mathbf x + \eta\nabla f$, with a step size $\eta$ small enough not to overshoot. **Newton's method** for a system $\mathbf F(\mathbf x) = \mathbf 0$ uses the Jacobian matrix $J$ of partial derivatives: $\mathbf x \leftarrow \mathbf x - J^{-1}\mathbf F$, which converges quadratically near a root.
:::

::: example
## Estimate the spread of a 10 V divider's 5 V output when both 10 kΩ resistors have a standard deviation of 50 Ω.

::: solution
1. **Sensitivities.** With $V = 10\frac{R_2}{R_1 + R_2}$:
   $$\begin{aligned} \frac{\partial V}{\partial R_1} &= -\frac{10R_2}{(R_1 + R_2)^2} \\ &= -2.5 \times 10^{-4}\ \text{V}/\Omega \\ \frac{\partial V}{\partial R_2} &= +2.5 \times 10^{-4}\ \text{V}/\Omega \end{aligned}$$
2. **Root-sum-square.**
   $$\begin{aligned} \sigma_V &= \sqrt2 \times 2.5 \times 10^{-4} \times 50 \\ &= 17.7\ \text{mV} \end{aligned}$$
3. **Check by simulation.** A Monte Carlo run with 100 000 random dividers gives 17.6 mV.
4. **Compare with adding.** Adding the sizes would give 25 mV, the worst case for errors in opposite directions.

**Answer:** the output spreads with a standard deviation of about 17.7 mV.
:::
:::

::: example
## Where do the circle $x^2 + y^2 = 4$ and the parabola $y = x^2$ cross?

::: solution
1. **Substitute the parabola.** With $y = x^2$ the circle becomes
   $$y + y^2 = 4$$
2. **Solve for $y$, then $x$.**
   $$\begin{aligned} y &= \frac{-1 + \sqrt{17}}{2} \\ &= 1.562 \\ x &= \pm1.250 \end{aligned}$$
3. **Check with Newton's method.** Newton's method on the pair, with
   $$J = \begin{bmatrix}2x & 2y\\-2x & 1\end{bmatrix}$$
   reaches the same point from $(1, 1)$ in five or six steps, each roughly doubling the number of correct digits.

**Answer:** they cross at $(\pm1.250, 1.562)$.
:::
:::

::: check
given: V = 5 | 12; R = 1 | 10; s = 0.5 | 1
answer: sqrt(2)*V/4*s/100
unit: V
tolerance: 0.5%

## A {V} V divider uses two equal {R} kΩ resistors, each with a standard deviation of {s}% of its value. What is the root-sum-square spread of the output?

::: right
Right. Each partial is $\frac{V}{4R}$, times $\sigma = sR/100$, and two equal independent terms give $\sqrt2$ times one: {answer}.
:::

::: misses
- [2*V/4*s/100] That's the worst case, adding the sizes.
- [any] Not yet. $\frac{\partial V_o}{\partial R_i} = \pm\frac{V}{4R}$ for equal resistors.
:::
:::

::: check
given: Rs = 50 | 75; Xs = 20 | 40
answer: -Xs
unit: Ω
tolerance: 0.5%

## A source has impedance $\given{Rs} + j\given{Xs}$ Ω. What load reactance delivers the most power?

::: right
Right. $X_L = -X_s$ = {answer} cancels the source's reactance, and then $R_L = R_s$.
:::

::: misses
- [Xs] The reactances must cancel, so the load's has the opposite sign.
- [any] Not yet. The power is largest when $(X_s + X_L)^2 = 0$.
:::
:::

::: check
kind: python

## Write `grad(f, x, h=1e-5)` returning the gradient of `f` at the NumPy point `x` by central differences. Set `g = grad(f, np.array([1.0, 2.0]))` for $f = x^2y + \sin y$.

```python starter
import numpy as np

def grad(f, x, h=1e-5):
    return np.zeros(len(x))

f = lambda p: p[0]**2 * p[1] + np.sin(p[1])
g = grad(f, np.array([1.0, 2.0]))
print(g)
```

```python solution
import numpy as np

def grad(f, x, h=1e-5):
    g = np.zeros(len(x))
    for k in range(len(x)):
        e = np.zeros(len(x))
        e[k] = h
        g[k] = (f(x + e) - f(x - e)) / (2 * h)
    return g

f = lambda p: p[0]**2 * p[1] + np.sin(p[1])
g = grad(f, np.array([1.0, 2.0]))
print(g)
```

```python tests
import numpy as np
assert np.allclose(g, [4, 1 + np.cos(2)], atol=1e-8), f"The gradient is (2xy, x^2 + cos y) = (4, 0.584); got {g}."
```

::: right
Right. Central differences agree with the exact gradient to about eight digits.
:::
:::

::: check
kind: python

## Simulate 100 000 dividers ($V_\text{in}$ = 10 V, two 10 kΩ resistors drawn with `rng.normal(1e4, 50, N)`, `rng = np.random.default_rng(1)`). Set `sd` to the output's standard deviation and `rss` to the root-sum-square estimate.

```python starter
import numpy as np

sd = rss = 0.0
print(sd, rss)
```

```python solution
import numpy as np

rng = np.random.default_rng(1)
N = 100000
R1 = rng.normal(1e4, 50, N)
R2 = rng.normal(1e4, 50, N)
V = 10 * R2 / (R1 + R2)
sd = V.std()
rss = np.sqrt(2) * 2.5e-4 * 50
print(sd, rss)
```

```python tests
assert abs(rss - 0.0176777) < 1e-6, f"The RSS estimate is sqrt(2) x 2.5e-4 x 50 = 0.01768 V; got {rss}."
assert abs(sd / rss - 1) < 0.02, f"Monte Carlo should agree with RSS within 2%; got {sd} against {rss}."
```

::: right
Right. For small, independent errors the linear estimate and the simulation agree; the simulation is what you'd trust for large or nonlinear ones.
:::
:::

::: check
kind: python

## Maximize the power $P(R, X) = \frac{50R}{(50 + R)^2 + (30 + X)^2}$ W by gradient ascent from $(R, X) = (10, 0)$ with numerical gradients and step size 2000, for 20 000 steps. Set `best` to the final $(R, X)$ and `Pmax` to the power there.

```python starter
import numpy as np

best = np.array([10.0, 0.0])
Pmax = 0.0
print(best, Pmax)
```

```python solution
import numpy as np

P = lambda R, X: 50 * R / ((50 + R)**2 + (30 + X)**2)
x = np.array([10.0, 0.0])
for _ in range(20000):
    gR = (P(x[0] + 1e-4, x[1]) - P(x[0] - 1e-4, x[1])) / 2e-4
    gX = (P(x[0], x[1] + 1e-4) - P(x[0], x[1] - 1e-4)) / 2e-4
    x = x + 2000 * np.array([gR, gX])
best = x
Pmax = P(*x)
print(best, Pmax)
```

```python tests
import numpy as np
assert np.allclose(best, [50, -30], atol=0.05), f"The conjugate match is R = 50, X = -30; got {best}."
assert abs(Pmax - 0.25) < 1e-6, f"The available power is 0.25 W; got {Pmax}."
```

::: right
Right. The climb ends at the conjugate match, $50 - 30j$ Ω, with the available power $\frac{|V|^2}{8R_s}$.
:::
:::

::: check
kind: python

## A plate's temperature is read at the points in the starter. Fit the plane $T = a + bx + cy$ by least squares and set `coef = (a, b, c)`.

```python starter
import numpy as np

x = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2.0])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2.0])
T = 20 + 3 * x - 1.5 * y + 0.05 * np.sin(7 * x + 3 * y)
coef = (0, 0, 0)
print(coef)
```

```python solution
import numpy as np

x = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2.0])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2.0])
T = 20 + 3 * x - 1.5 * y + 0.05 * np.sin(7 * x + 3 * y)
A = np.column_stack([np.ones_like(x), x, y])
coef = tuple(np.linalg.lstsq(A, T, rcond=None)[0])
print(coef)
```

```python tests
import numpy as np
assert np.allclose(coef, [20, 3, -1.5], atol=0.1), f"The plane is about 20 + 3x - 1.5y; got {coef}."
A = np.column_stack([np.ones_like(x), x, y])
assert np.allclose(A.T @ (T - A @ np.array(coef)), 0, atol=1e-9), "The residual should be perpendicular to the columns."
```

::: right
Right. The fitted plane is the tangent-plane model of the temperature field: its slopes are the gradient.
:::
:::

::: check
kind: python

## Solve $x^2 + y^2 = 4$, $y = x^2$ by Newton's method from $(1, 1)$, 20 steps, using the Jacobian. Set `p` to the solution.

```python starter
import numpy as np

p = np.array([1.0, 1.0])
print(p)
```

```python solution
import numpy as np

p = np.array([1.0, 1.0])
for _ in range(20):
    F = np.array([p[0]**2 + p[1]**2 - 4, p[1] - p[0]**2])
    J = np.array([[2 * p[0], 2 * p[1]], [-2 * p[0], 1]])
    p = p - np.linalg.solve(J, F)
print(p)
```

```python tests
import math
import numpy as np
ys = (-1 + math.sqrt(17)) / 2
assert np.allclose(p, [math.sqrt(ys), ys]), f"The crossing is (1.250, 1.562); got {p}."
```

::: right
Right. Newton's method in two variables is the same idea as in one, with the Jacobian matrix in place of the derivative.
:::
:::

::: explain
## When would you trust a Monte Carlo tolerance analysis over the root-sum-square formula?

::: model
The root-sum-square formula linearizes the output around its nominal value and assumes independent errors, so it's exact only for small errors and nearly linear functions. If tolerances are large, the function curves enough that the linear estimate misses, and it can't capture effects that only appear at extremes, like a transistor saturating or a filter's peak moving. Correlated errors, such as resistors from the same reel drifting together with temperature, also break the formula unless the correlations are included. Monte Carlo simply evaluates the real function on many random samples, so it handles all of these, at the cost of computation and a statistical error that shrinks as $1/\sqrt N$.
:::
:::

::: practice

::: check
given: V = 1..30; s = 0.1..5
answer: sqrt(2)*V/4*s/100
unit: V
tolerance: 0.5%

## RSS spread in volts of a {V} V equal-resistor divider with {s}% resistors?

::: misses
- [any] $\sqrt2\frac V4\frac{s}{100}$.
:::
:::

::: check
given: Rs = 1..100; Xs = 1..100
answer: Rs
tolerance: 0.5%

## Best load resistance for a source of $\given{Rs} + j\given{Xs}$ Ω?

::: misses
- [any] The conjugate match: $R_L = R_s$.
:::
:::
:::
