---
title: "Lab: optimization in code"
heading: Finding the best value when calculus gives no tidy answer
eyebrow: A5 · Lesson 31 · Lab: optimization in code
xp: 60
---

::: hook
Setting a derivative to zero finds the best value when you can solve the resulting equation. Often you can't: a solar panel's power curve has an exponential in it, and a choice from a list of standard resistors has no derivative at all. Then the computer searches. In this lab you'll write a golden-section search that closes in on a maximum without derivatives, check it against problems you can solve by hand, track a solar panel's maximum power point, and pick the best standard resistors by brute force.
:::

::: play
- The curve is a solar panel's power, $P = V\left(I_{sc} - I_0(e^{V/nV_T} - 1)\right)$, against its voltage. The current is nearly constant until the diode term takes over near open circuit.
- The marker is the maximum power point. A golden-section search started on $[0, 25]$ V closes in on it by discarding, at each step, the part of the bracket that can't hold the peak.
- Step $k$ up. The readout is the bracket's width after $k$ steps: it shrinks by the same factor, 0.618, every step, wherever the peak is.
:::

```sim plot
view: graph
x: V = 0..28 V
y: P = 0..130 W
slider: k = 0..20 step 1 = 0
plot: V*(5 - 1e-9*(exp(V/(0.0257*1.3*36)) - 1)) | samples: 400 | label: panel power
marker: V = 23.2386 | label: maximum power
readout: bracket width = 25*0.618034^k | digits: 4
```

::: predict
## A golden-section search starts with a bracket 30 V wide. About how many steps until it's narrower than 1 µV?

- [ ] 25
- [x] 36
- [ ] 50
- [ ] 1000

::: reveal
About 36. Each step multiplies the width by 0.618, so it takes $\frac{\ln(10^{-6}/30)}{\ln 0.618} = 35.8$ steps. That's a little slower than bisection's halving, but it needs no derivative and only one new function value per step.
:::
:::

::: nameit
## Golden-section search

To maximize a function with a single peak on $[a, b]$, compare it at two inner points, $c = b - g(b - a)$ and $d = a + g(b - a)$, with $g = \frac{\sqrt5 - 1}{2} = 0.618$.
- If $f(c) > f(d)$, the peak can't be in $(d, b]$: set $b = d$.
- Otherwise it can't be in $[a, c)$: set $a = c$.

The golden ratio is chosen so that one of the old inner points becomes an inner point of the new bracket, so each step costs just one new evaluation. The bracket shrinks by 0.618 each time, whatever the function looks like.

## Checking a search

A numerical optimizer should be tested on a problem with a known answer first: $P(V) = 8V - 0.004V^3$ peaks at $V = \sqrt{8/0.012} = 25.82$, and $P(R) = \frac{E^2R}{(R + r)^2}$ peaks at $R = r$.

## Discrete choices

Standard resistor values come from a list, so "the best pair" is found by trying them all: for a divider with 12 values per decade over a decade, that's only 144 pairs, a trivial loop for a computer. When there are many parts, smarter searches are needed, but brute force is the honest baseline.
:::

::: example
## Check the search on $P(V) = 8V - 0.004V^3$ over $[10, 40]$.

::: solution
1. **Exact peak.**
   $$P' = 8 - 0.012V^2$$
   is zero at $V = 25.820$, where $P = 137.71$ W.
2. **Search result.** A golden-section search from $[10, 40]$ to a tolerance of $10^{-9}$ returns 25.819 889, agreeing to the last digit shown.
3. **What it shows.** Now the code can be trusted on a curve without a formula.

**Answer:** the search returns 25.819 889, matching the exact peak at $V = 25.820$, where $P = 137.71$ W.
:::
:::

::: example
## A panel has $I_{sc}$ = 5 A, $I_0 = 10^{-9}$ A and $nV_T$ = 1.203 V (36 cells). Where is its maximum power point?

::: solution
1. **Why a search.** Setting $\frac{dP}{dV} = 0$ gives an equation with $V$ both inside and outside an exponential, which can't be solved in closed form.
2. **Search.** A golden-section search on $[0, 25]$ V finds the peak at 23.24 V, delivering 110.5 W.
3. **Open-circuit voltage.**
   $$\begin{aligned} V_{oc} &= nV_T\ln(I_{sc}/I_0 + 1) \\ &= 26.87\ \text{V} \end{aligned}$$
4. **Compare.** The best voltage is about 87% of it, a common rule of thumb for solar trackers.

**Answer:** the maximum power point is at 23.24 V, delivering 110.5 W.
:::
:::

::: check
given: W = 10 | 30 | 100; tol = 0.001 | 0.000001
answer: ceil(ln(tol/W)/ln(0.618034))
tolerance: 0

## A golden-section search starts with a bracket {W} wide. How many steps until it's narrower than {tol}?

::: right
Right. $0.618^n \cdot W \le$ tol after {answer} steps.
:::

::: misses
- [ceil(ln(tol/W)/ln(0.5))] That's bisection's count. Golden section shrinks by 0.618.
- [floor(ln(tol/W)/ln(0.618034))] One step short: the width is still just above the tolerance.
- [any] Not yet. Solve $0.618^n W = $ tol for $n$ and round up.
:::
:::

::: check
given: a = 4 | 8 | 12; b = 0.002 | 0.004
answer: sqrt(a/(3*b))
tolerance: 0.5%

## Where does $P(V) = \given{a}V - \given{b}V^3$ have its maximum?

::: right
Right. $P' = a - 3bV^2 = 0$ gives $V = \sqrt{a/3b}$ = {answer}.
:::

::: misses
- [sqrt(a/b)] Differentiate $V^3$: it's $3V^2$.
- [any] Not yet. Set the derivative to zero.
:::
:::

::: check
kind: python

## Write `golden_max(f, a, b, tol=1e-9)` returning the location of the maximum of a single-peaked `f` on `[a, b]`. Set `V = golden_max(lambda V: 8*V - 0.004*V**3, 10, 40)`.

```python starter
import math

def golden_max(f, a, b, tol=1e-9):
    return (a + b) / 2

V = golden_max(lambda V: 8*V - 0.004*V**3, 10, 40)
print(V)
```

```python solution
import math

def golden_max(f, a, b, tol=1e-9):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol:
        if fc > fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2

V = golden_max(lambda V: 8*V - 0.004*V**3, 10, 40)
print(V)
```

```python tests
import math
assert abs(V - math.sqrt(8 / 0.012)) < 1e-6, f"The peak is at sqrt(8/0.012) = 25.8199; got {V}."
assert abs(golden_max(lambda R: 100 * R / (R + 50)**2, 1, 500) - 50) < 1e-5, "Load power peaks when R equals the source's 50 ohms."
assert abs(golden_max(lambda x: -(x - 0.3)**2, 0, 1) - 0.3) < 1e-7, "A downward parabola peaks at its vertex."
calls = []
golden_max(lambda x: calls.append(x) or -(x - 2)**2, 0, 10, 1e-6)
assert len(calls) < 40, f"Each step should cost one new evaluation; it used {len(calls)}."
```

::: right
Right. Reusing one inner point each step is what makes the golden ratio the right choice.
:::
:::

::: check
kind: python
given: Isc = 3 | 5 | 8

## A panel has short-circuit current `Isc` = {Isc} A, $I_0 = 10^{-9}$ A and $nV_T$ = 1.203 V. With your `golden_max` (in the starter), set `Vmp` to the voltage of maximum power on $[0, 30]$, `Pmp` to that power, and `ratio` to `Vmp` divided by the open-circuit voltage $nV_T\ln(I_{sc}/I_0 + 1)$.

```python starter
import math

def golden_max(f, a, b, tol=1e-9):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol:
        if fc > fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2

Vmp = Pmp = ratio = 0
print(Vmp, Pmp, ratio)
```

```python solution
import math

def golden_max(f, a, b, tol=1e-9):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol:
        if fc > fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2

I0, nVt = 1e-9, 1.203
P = lambda V: V * (Isc - I0 * (math.exp(V / nVt) - 1))
Voc = nVt * math.log(Isc / I0 + 1)
Vmp = golden_max(P, 0, Voc)
Pmp = P(Vmp)
ratio = Vmp / Voc
print(Vmp, Pmp, ratio)
```

```python tests
import math
I0, nVt = 1e-9, 1.203
P = lambda V: V * (Isc - I0 * (math.exp(V / nVt) - 1))
h = 1e-4
assert abs((P(Vmp + h) - P(Vmp - h)) / (2 * h)) < 1e-3, f"At the maximum the slope of P should be zero; got {(P(Vmp + h) - P(Vmp - h)) / (2 * h)}."
assert abs(Pmp - P(Vmp)) < 1e-9 and 0.8 < ratio < 0.9, f"The best voltage is usually 80 to 90% of open circuit; got {ratio:.3f}."
```

::: right
Right. A maximum power point tracker does this continuously as the light changes.
:::
:::

::: check
kind: python
given: k = 0.3 | 0.55 | 0.82

## Using the E12 list in the starter (1 kΩ to 8.2 kΩ), try every pair of a top resistor `R1` and bottom `R2` and set `best` to the `(R1, R2)` whose divider ratio $R_2/(R_1 + R_2)$ is closest to `k` = {k}, and `err` to how far off its ratio is.

```python starter
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
E12 = [x * 1000 for x in E12]

best = (0, 0)
err = 1
print(best, err)
```

```python solution
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
E12 = [x * 1000 for x in E12]

best, err = None, float("inf")
for R1 in E12:
    for R2 in E12:
        e = abs(R2 / (R1 + R2) - k)
        if e < err:
            best, err = (R1, R2), e
print(best, err)
```

```python tests
want = min(abs(b / (a + b) - k) for a in E12 for b in E12)
assert abs(err - want) < 1e-15, f"The closest E12 ratio misses {k} by {want:.5f}; got {err}."
R1, R2 = best
assert abs(abs(R2 / (R1 + R2) - k) - err) < 1e-15, "best should be the pair that achieves err."
```

::: right
Right. 144 tries take no time at all, and brute force can't miss the best pair.
:::
:::

::: check
kind: python

## A golden-section search assumes one peak. $f(x) = e^{-(x - 1)^2} + 1.3e^{-((x - 2.8)/0.08)^2}$ has two on $[0, \pi]$: a broad low one and a narrow tall one. Write `global_max(f, a, b, n)`: evaluate $f$ at `n` + 1 evenly spaced points, take the best one, then run your `golden_max` (in the starter) on the interval one grid step either side of it. Set `x1 = golden_max(f, 0, math.pi)` and `x2 = global_max(f, 0, math.pi, 50)`.

```python starter
import math

def golden_max(f, a, b, tol=1e-10):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol:
        if fc > fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2

def global_max(f, a, b, n):
    return golden_max(f, a, b)

f = lambda x: math.exp(-(x - 1)**2) + 1.3 * math.exp(-((x - 2.8) / 0.08)**2)
x1 = golden_max(f, 0, math.pi)
x2 = global_max(f, 0, math.pi, 50)
print(x1, f(x1), x2, f(x2))
```

```python solution
import math

def golden_max(f, a, b, tol=1e-10):
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = f(c), f(d)
    while b - a > tol:
        if fc > fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = f(c)
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = f(d)
    return (a + b) / 2

def global_max(f, a, b, n):
    h = (b - a) / n
    xs = [a + k * h for k in range(n + 1)]
    best = max(xs, key=f)
    return golden_max(f, max(a, best - h), min(b, best + h))

f = lambda x: math.exp(-(x - 1)**2) + 1.3 * math.exp(-((x - 2.8) / 0.08)**2)
x1 = golden_max(f, 0, math.pi)
x2 = global_max(f, 0, math.pi, 50)
print(x1, f(x1), x2, f(x2))
```

```python tests
import math
f = lambda x: math.exp(-(x - 1)**2) + 1.3 * math.exp(-((x - 2.8) / 0.08)**2)
fine = max((k * math.pi / 100000 for k in range(100001)), key=f)
assert abs(x2 - fine) < 1e-4 and f(x2) >= f(fine) - 1e-9, f"The global maximum is near {fine:.4f}; got {x2:.4f}."
assert f(x1) < f(x2) - 0.1, "Plain golden-section search, started over the whole interval, lands on the lower peak here."
```

::: right
Right. A coarse look first, then a precise search: the plain search found the lower of the two peaks.
:::
:::

::: explain
## Why does a golden-section search need the function to have a single peak in the bracket, and what happens if it doesn't?

::: model
Each step compares the function at two inner points and throws away the outer part beyond the lower one, on the reasoning that if the function is lower there, the peak must be on the other side. That reasoning is only valid if the function rises to one peak and then falls: then a lower value at $d$ than at $c$ proves the peak isn't to the right of $d$. With two peaks in the bracket, the comparison can throw away the part holding the higher one, and the search converges confidently to a lesser, local maximum. It never reports a problem, because it never looks at the discarded part again. That's why a search is started from a bracket that a plot or physical reasoning says holds a single peak, or run from several starting brackets and the best answer kept.
:::
:::

::: practice

::: check
given: W = 1..1000; tol = 0.000001..0.1
answer: ceil(ln(tol/W)/ln(0.618034))
tolerance: 0

## Golden-section steps from width {W} to below {tol}?

::: misses
- [any] The smallest $n$ with $0.618^nW \le$ tol.
:::
:::

::: check
given: a = 1..20; b = 0.001..0.1
answer: sqrt(a/(3*b))
tolerance: 0.5%

## Peak of $\given{a}V - \given{b}V^3$?

::: misses
- [any] $\sqrt{a/3b}$.
:::
:::
:::
