---
title: "Converter simulation lab: switching and averaged models"
heading: Simulating a synchronous buck switch by switch with Runge–Kutta, checking its ripple against the formulas of lesson 3, simulating the averaged model with a tenth of the steps, and measuring the overshoot of a duty-cycle step against the second-order transfer function
eyebrow: S11 · Lesson 50 · Converter simulation lab
xp: 60
---

::: hook
Lesson 16 replaced the switch by its average and got a linear model that's easy to analyze and fast to simulate. In this lab you'll test that trade directly. You'll simulate a 12 V buck both ways, check the switching model's ripple against the formulas you derived by hand, and find where the averaged model is exact, where it's off, and by how much.
:::

::: predict
## Starting from rest, the switching model's output voltage, averaged over each cycle, runs slightly ahead of the averaged model during the start-up transient. Why?

- [ ] The averaged model leaves out the inductor
- [x] The switch is on during the first part of each cycle, so the applied volt-seconds arrive earlier than a steady D·VG would deliver them
- [ ] Runge–Kutta is less accurate with bigger steps
- [ ] The averaged model's steady state is wrong

::: reveal
With trailing-edge modulation the switch node sits at VG for the first DT of each cycle. The average over the cycle is the same, but its center falls $(1 - D)T/2$ before the cycle's center, a small time advance. During the fast start-up it shows as a difference of several percent; in steady state and for slow changes it vanishes. That's the modulator delay that more refined averaged models include.
:::
:::

::: nameit
## The converter

A synchronous buck with $V_g$ = 12 V, L = 22 µH, C = 47 µF, R = 2 Ω and $f_s$ = 100 kHz. The state is the inductor current and capacitor voltage:

$$L\frac{di_L}{dt} = v_s - v, \qquad C\frac{dv}{dt} = i_L - \frac{v}{R}$$

where the switch node $v_s$ is $V_g$ for the first DT of each cycle and 0 for the rest (both switches are ideal and the current may reverse).

## The averaged model

Replace $v_s$ by its average $DV_g$. The model is linear and time-invariant, with the transfer function of lesson 17, a resonance at $1/2\pi\sqrt{LC}$ = 4.95 kHz and damping $\zeta = \frac{1}{2R}\sqrt{L/C}$ = 0.171.

## What to check

- The switching model in steady state: average $DV_g$, inductor ripple $(V_g - V)D/(Lf_s)$, output ripple $\Delta i_L/(8Cf_s)$.
- The averaged model against its exact solution, and its peak from rest, $DV_g(1 + e^{-\pi\zeta/\sqrt{1 - \zeta^2}})$.
- A duty step's overshoot, the same expression, independent of the step's size and direction.
:::

::: example
## What do the two models give at D = 0.3?

::: solution
1. **Switching model at steady state.** It settles to an average of 3.6000 V, with 1.147 A of inductor ripple (the formula gives 1.145) and 30.5 mV of output ripple (the formula gives 30.5).
2. **Averaged model from rest.** It peaks at 5.686 V, using 2,000 steps against the switching model's 20,000. The formula gives
   $$\begin{aligned} V_\text{pk} &= 3.6 \times 1.5796 \\ &= 5.687\ \text{V} \end{aligned}$$
3. **During start-up.** The switching model's cycle averages lead by up to 0.31 V (8.5% of the final value) four cycles in; by the time the ringing has died out the two agree.

**Answer:** both models agree with the formulas: the switching model settles at 3.6000 V with 1.147 A and 30.5 mV of ripple, and the averaged model peaks at 5.686 V from rest.
:::
:::

::: example
## A duty step from 0.3 to 0.4 overshoots by how much in each model?

::: solution
1. **Averaged model.** It overshoots by 0.5796 of the step, matching
   $$e^{-\pi\zeta/\sqrt{1 - \zeta^2}}$$
   with ζ = 0.171.
2. **Switching model.** Its cycle averages overshoot by 0.5753, 0.75% less.
3. **A small step.** For a small step (0.6 to 0.65) the difference shrinks to 0.07%.
4. **Which to use.** For loop design at crossovers well below the switching frequency, the averaged model is the right tool.

**Answer:** 0.5796 of the step in the averaged model and 0.5753 in the switching model, 0.75% less.
:::
:::

::: check
kind: python

## Step 1. Write `simulate_switched(D)`: the buck pulse by pulse.

```python starter
import numpy as np

VG, L, C, R, FS = 12.0, 22e-6, 47e-6, 2.0, 100e3   # volts, henries, farads, ohms, hertz

def rk4_step(f, x, h):
    # One classical Runge-Kutta step for a state x = [iL, v] and derivative function f(x).
    k1 = f(x)
    k2 = f([x[0] + h/2*k1[0], x[1] + h/2*k1[1]])
    k3 = f([x[0] + h/2*k2[0], x[1] + h/2*k2[1]])
    k4 = f([x[0] + h*k3[0], x[1] + h*k3[1]])
    return [x[0] + h/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0]), x[1] + h/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])]

def simulate_switched(D, cycles=200, steps=100):
    # Simulate the synchronous buck from iL = v = 0 with the switch node at VG for the first
    # round(D*steps) steps of each cycle and at 0 V for the rest. Step size 1/(FS*steps).
    # Return numpy arrays t, iL, v of length cycles*steps + 1 (the start included).
    t = np.arange(cycles*steps + 1)/(FS*steps)
    return t, np.zeros_like(t), np.zeros_like(t)

t, iL, v = simulate_switched(0.3)
print("average of the last cycle:", np.mean(v[-101:-1]))
```

```python solution
import numpy as np

VG, L, C, R, FS = 12.0, 22e-6, 47e-6, 2.0, 100e3   # volts, henries, farads, ohms, hertz

def rk4_step(f, x, h):
    # One classical Runge-Kutta step for a state x = [iL, v] and derivative function f(x).
    k1 = f(x)
    k2 = f([x[0] + h/2*k1[0], x[1] + h/2*k1[1]])
    k3 = f([x[0] + h/2*k2[0], x[1] + h/2*k2[1]])
    k4 = f([x[0] + h*k3[0], x[1] + h*k3[1]])
    return [x[0] + h/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0]), x[1] + h/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])]

def simulate_switched(D, cycles=200, steps=100):
    h = 1/(FS*steps)
    n_on = round(D*steps)
    x = [0.0, 0.0]
    iL, v = [0.0], [0.0]
    for k in range(cycles):
        for s in range(steps):
            vs = VG if s < n_on else 0.0
            x = rk4_step(lambda y: [(vs - y[1])/L, (y[0] - y[1]/R)/C], x, h)
            iL.append(x[0])
            v.append(x[1])
    t = np.arange(cycles*steps + 1)*h
    return t, np.array(iL), np.array(v)

t, iL, v = simulate_switched(0.3)
print("average of the last cycle:", np.mean(v[-101:-1]))
```

```python tests
for D in (0.3, 0.6):
    t, iL, v = simulate_switched(D)
    assert len(t) == len(iL) == len(v) == 20001, f"Return cycles*steps + 1 = 20001 samples, the start included; got {len(v)}."
    V = D*VG
    avg = np.mean(v[-101:-1])
    assert abs(avg/V - 1) < 1e-3, f"At D = {D} the last cycle should average D·VG = {V:.3f} V once the start-up transient has died away; got {avg:.4f} V."
    di, di_f = iL[-101:].max() - iL[-101:].min(), (VG - V)*D/(L*FS)
    assert abs(di/di_f - 1) < 0.01, f"At D = {D} the inductor ripple should be (VG − V)D/(L·FS) = {di_f:.4f} A peak to peak; got {di:.4f} A."
    dv, dv_f = v[-101:].max() - v[-101:].min(), di_f/(8*C*FS)
    assert abs(dv/dv_f - 1) < 0.02, f"At D = {D} the output ripple should be ΔiL/(8·C·FS) = {1000*dv_f:.2f} mV; got {1000*dv:.2f} mV."
```

::: right
Right. Your switching simulation settles to D·VG with the ripple of lesson 3 at both duty cycles.
:::
:::

::: check
kind: python

## Step 2. Write `simulate_averaged(D)`: the same converter with the switch averaged.

```python starter
import numpy as np

VG, L, C, R, FS = 12.0, 22e-6, 47e-6, 2.0, 100e3   # volts, henries, farads, ohms, hertz

def rk4_step(f, x, h):
    # One classical Runge-Kutta step for a state x = [iL, v] and derivative function f(x).
    k1 = f(x)
    k2 = f([x[0] + h/2*k1[0], x[1] + h/2*k1[1]])
    k3 = f([x[0] + h/2*k2[0], x[1] + h/2*k2[1]])
    k4 = f([x[0] + h*k3[0], x[1] + h*k3[1]])
    return [x[0] + h/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0]), x[1] + h/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])]

def simulate_averaged(D, cycles=200, steps=10):
    # The averaged model replaces the switch node by its average D*VG. Simulate it from rest with
    # step 1/(FS*steps) and return t, iL, v of length cycles*steps + 1.
    t = np.arange(cycles*steps + 1)/(FS*steps)
    return t, np.zeros_like(t), np.zeros_like(t)

t, iL, v = simulate_averaged(0.3)
print("peak:", v.max(), "final:", v[-1])
```

```python solution
import numpy as np

VG, L, C, R, FS = 12.0, 22e-6, 47e-6, 2.0, 100e3   # volts, henries, farads, ohms, hertz

def rk4_step(f, x, h):
    # One classical Runge-Kutta step for a state x = [iL, v] and derivative function f(x).
    k1 = f(x)
    k2 = f([x[0] + h/2*k1[0], x[1] + h/2*k1[1]])
    k3 = f([x[0] + h/2*k2[0], x[1] + h/2*k2[1]])
    k4 = f([x[0] + h*k3[0], x[1] + h*k3[1]])
    return [x[0] + h/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0]), x[1] + h/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])]

def simulate_averaged(D, cycles=200, steps=10):
    h = 1/(FS*steps)
    x = [0.0, 0.0]
    iL, v = [0.0], [0.0]
    for k in range(cycles*steps):
        x = rk4_step(lambda y: [(D*VG - y[1])/L, (y[0] - y[1]/R)/C], x, h)
        iL.append(x[0])
        v.append(x[1])
    t = np.arange(cycles*steps + 1)*h
    return t, np.array(iL), np.array(v)

t, iL, v = simulate_averaged(0.3)
print("peak:", v.max(), "final:", v[-1])
```

```python tests
A = np.array([[0, -1/L], [1/C, -1/(R*C)]])
lam, P = np.linalg.eig(A)
Pinv = np.linalg.inv(P)
for D in (0.3, 0.6):
    t, iL, v = simulate_averaged(D)
    assert len(v) == 2001, f"Return cycles*steps + 1 = 2001 samples; got {len(v)}."
    xss = np.array([D*VG/R, D*VG])
    for k in (37, 150, 2000):
        x = xss + (P @ np.diag(np.exp(lam*t[k])) @ Pinv @ (-xss)).real
        assert abs(iL[k] - x[0]) < 1e-6 and abs(v[k] - x[1]) < 1e-6, f"At D = {D}, t = {1e6*t[k]:.0f} µs the averaged model's exact solution is iL = {x[0]:.6f} A, v = {x[1]:.6f} V; got {iL[k]:.6f} A, {v[k]:.6f} V."
    z = np.sqrt(L/C)/(2*R)
    peak = D*VG*(1 + np.exp(-np.pi*z/np.sqrt(1 - z*z)))
    assert abs(v.max()/peak - 1) < 1e-3, f"From rest the output should peak at D·VG(1 + e^(−πζ/√(1−ζ²))) = {peak:.4f} V; got {v.max():.4f} V."
```

::: right
Right. Your averaged model matches its exact solution and peaks where the second-order formula says, with a tenth of the steps.
:::
:::

::: check
kind: python

## Step 3. Write `duty_step_overshoot(D1, D2)`: a small-signal step on the averaged model.

```python starter
import numpy as np

VG, L, C, R, FS = 12.0, 22e-6, 47e-6, 2.0, 100e3   # volts, henries, farads, ohms, hertz

def rk4_step(f, x, h):
    # One classical Runge-Kutta step for a state x = [iL, v] and derivative function f(x).
    k1 = f(x)
    k2 = f([x[0] + h/2*k1[0], x[1] + h/2*k1[1]])
    k3 = f([x[0] + h/2*k2[0], x[1] + h/2*k2[1]])
    k4 = f([x[0] + h*k3[0], x[1] + h*k3[1]])
    return [x[0] + h/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0]), x[1] + h/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])]

def duty_step_overshoot(D1, D2, R=R, cycles=300, steps=10):
    # Start the averaged model in its steady state at duty D1 (iL = D1*VG/R, v = D1*VG), step the
    # duty to D2, simulate, and return the overshoot max over t of (v - V2)/(V2 - V1), where
    # V1 = D1*VG and V2 = D2*VG. It works for steps up and down.
    return 0.0

print(duty_step_overshoot(0.3, 0.4))
```

```python solution
import numpy as np

VG, L, C, R, FS = 12.0, 22e-6, 47e-6, 2.0, 100e3   # volts, henries, farads, ohms, hertz

def rk4_step(f, x, h):
    # One classical Runge-Kutta step for a state x = [iL, v] and derivative function f(x).
    k1 = f(x)
    k2 = f([x[0] + h/2*k1[0], x[1] + h/2*k1[1]])
    k3 = f([x[0] + h/2*k2[0], x[1] + h/2*k2[1]])
    k4 = f([x[0] + h*k3[0], x[1] + h*k3[1]])
    return [x[0] + h/6*(k1[0] + 2*k2[0] + 2*k3[0] + k4[0]), x[1] + h/6*(k1[1] + 2*k2[1] + 2*k3[1] + k4[1])]

def duty_step_overshoot(D1, D2, R=R, cycles=300, steps=10):
    h = 1/(FS*steps)
    V1, V2 = D1*VG, D2*VG
    x = [V1/R, V1]
    worst = 0.0
    for k in range(cycles*steps):
        x = rk4_step(lambda y: [(D2*VG - y[1])/L, (y[0] - y[1]/R)/C], x, h)
        worst = max(worst, (x[1] - V2)/(V2 - V1))
    return worst

print(duty_step_overshoot(0.3, 0.4))
```

```python tests
for (D1, D2, r) in ((0.3, 0.4, 2.0), (0.5, 0.4, 2.0), (0.4, 0.5, 4.0), (0.6, 0.5, 1.0)):
    z = np.sqrt(L/C)/(2*r)
    want = np.exp(-np.pi*z/np.sqrt(1 - z*z))
    got = duty_step_overshoot(D1, D2, R=r)
    assert abs(got/want - 1) < 2e-3, f"A duty step {D1} → {D2} with R = {r} Ω has ζ = {z:.4f}, so the overshoot should be e^(−πζ/√(1−ζ²)) = {want:.4f}; got {got:.4f}."
```

::: right
Right. The overshoot depends only on ζ, for steps up or down and at any load.
:::
:::

::: explain
## When is the averaged model good enough, and when do you need the switching simulation?

::: model
The averaged model throws away everything that happens within a switching period: the ripple and the timing of the pulses within each cycle. That's harmless whenever the quantities of interest change slowly compared with the switching period, which covers steady-state averages, efficiency trends and control loops with crossover well below the switching frequency, the usual design rule. It loses accuracy for fast transients, as the start-up here shows, and it can't predict the ripple itself, peak currents for saturation and current limits, subharmonic oscillation in current-mode control, or anything near half the switching frequency. Those need the switching simulation, which costs far more steps but sees each pulse.
:::
:::

::: practice

::: check
given: g = 5 | 12 | 24; D = 0.2 | 0.4 | 0.7; L = 4.7 | 22; f = 100 | 500
answer: (g - D*g)*D/(L*1e-6*f*1e3)
unit: A
tolerance: 0.5%

## Inductor ripple of a buck: {g} V in, D = {D}, {L} µH, {f} kHz?

::: misses
- [any] $(V_g - V)D/(Lf_s)$.
:::
:::

::: check
given: d = 0.3 | 1.5; C = 22 | 100; f = 100 | 400
answer: d/(8*C*1e-6*f*1e3)*1000
unit: mV
tolerance: 0.5%

## Output ripple: {d} A of inductor ripple, {C} µF, {f} kHz?

::: misses
- [any] $\Delta i_L/(8Cf_s)$.
:::
:::

::: check
given: L = 10 | 47; C = 22 | 220; R = 1 | 5
answer: exp(-pi*(sqrt(L/C)/(2*R))/sqrt(1 - (sqrt(L/C)/(2*R))^2))
tolerance: 0.5%

## Overshoot of the averaged buck after a duty step: {L} µH, {C} µF, {R} Ω?

::: misses
- [any] $e^{-\pi\zeta/\sqrt{1 - \zeta^2}}$ with $\zeta = \frac{1}{2R}\sqrt{L/C}$.
:::
:::
:::
