Sub topic 14
Checking results with a numerical simulation
Why check a transient numerically
You can solve a first-order transient with the general formula and still make mistakes. A sign can flip, a time constant can use the wrong resistance, or an initial value can be wrong. A short numerical simulation gives an independent answer. If it matches your formula, you have strong evidence the formula is right. If it does not, one of the two is wrong, and the mismatch tells you where to look.
This chapter assumes you have these prerequisites:
- The RC and RL step responses and the time constant (tau = RC or L/R).
- The general formula x(t) = xfinal + (xinitial - x_final) e^(-t/tau).
- Basic Python, including loops and the
mathmodule.
Every first-order transient in this tutorial obeys the same differential equation:
dx/dt = (x_final - x)/tau
Here x is the capacitor voltage or inductor current. The simulation integrates this equation step by step and compares the result with the closed-form solution.
The idea: marching in small time steps
A differential equation gives the slope of x at every moment. If you know x now and the slope now, you can estimate x a short time dt later:
x(t + dt) ≈ x(t) + dt · (dx/dt)
This is the forward Euler method. You apply it repeatedly, and each step starts from the value the previous step produced. For the RC step response, the slope is (V - v)/tau, so each step is:
v_next = v + dt · (V - v)/tau
The method is simple and easy to write. It is also approximate, because it assumes the slope stays constant during the whole step. The slope actually shrinks as v approaches V, so the method introduces a small error each step.
Worked example: RC charging
Take R = 10 kΩ, C = 100 nF, and a 5 V step. Then tau = RC = 1 ms. The analytic answer is v_C(t) = 5(1 - e^(-t/tau)). The code below integrates for 5 tau with 100 steps per time constant and compares the result with the formula.
import math
R, C, V = 10e3, 100e-9, 5.0
tau = R * C
dt = tau / 100
steps = 500 # simulate 5 tau
v = 0.0
for _ in range(steps):
v += dt * (V - v) / tau # forward Euler on dv/dt = (V - v)/tau
t = steps * dt
exact = V * (1 - math.exp(-t / tau))
print(f"Euler: {v:.4f} V, exact: {exact:.4f} V")The Euler value comes out slightly below the exact value, about 4.9667 V against 4.9663 V. The two agree to about three decimal places. That agreement confirms that the differential equation, the time constant, and the closed-form solution are consistent.
Notice what the code needs: the initial value (0 V), the final value (V), and tau. These are the same three numbers the general formula needs. The simulation does not replace your analysis. It checks that those three numbers produce the curve you expect.
Choosing the time step
The time step dt controls the accuracy. A useful rule is to pick dt as a small fraction of tau, such as tau/100. The next table shows what happens for the RC example when you change the step size and simulate to t = tau.
| Step size dt | Steps to reach tau | Approximate error at t = tau |
|---|---|---|
| tau / 10 | 10 | about 0.0185 V |
| tau / 100 | 100 | about 0.0018 V |
| tau / 1000 | 1000 | about 0.0002 V |
Reducing dt by a factor of 10 reduces the error by about a factor of 10. This is the behavior of a first-order method: the error is proportional to dt.
Checking the error systematically
Instead of reading one printed number, compute the largest difference between the simulation and the formula over the whole interval. This catches errors that appear only at some times, such as a wrong initial value.
import math
def simulate_rc(R, C, V, v0, t_end, dt):
"""Return lists of times and Euler capacitor voltages."""
tau = R * C
times, volts = [0.0], [v0]
v, t = v0, 0.0
n = round(t_end / dt)
for _ in range(n):
v += dt * (V - v) / tau
t += dt
times.append(t)
volts.append(v)
return times, volts
def analytic_rc(R, C, V, v0, t):
tau = R * C
return V + (v0 - V) * math.exp(-t / tau)
R, C, V, v0 = 10e3, 100e-9, 5.0, 1.0
tau = R * C
times, volts = simulate_rc(R, C, V, v0, 5 * tau, tau / 100)
worst = max(abs(v - analytic_rc(R, C, V, v0, t))
for t, v in zip(times, volts))
print(f"Largest error over 5 tau: {worst * 1000:.2f} mV")This version starts the capacitor at 1 V, so it also tests the general formula with a nonzero initial value. The largest error should be a few millivolts, which is small compared with the 4 V swing. If you saw an error of hundreds of millivolts, you would suspect a mistake in the formula or the code.
The same method for RL circuits
The RL step response has the same form, with current in place of voltage and tau = L/R. The slope is (ifinal - i)/tau, where ifinal = V/R. The same loop works with different names.
import math
R, L, V = 100.0, 10e-3, 12.0
tau = L / R # 100 microseconds
i_final = V / R # 120 mA
dt = tau / 100
i = 0.0
for step in range(1, 501):
i += dt * (i_final - i) / tau
if step % 100 == 0:
t = step * dt
exact = i_final * (1 - math.exp(-t / tau))
print(f"t = {step // 100} tau: Euler {i * 1000:.2f} mA, "
f"exact {exact * 1000:.2f} mA")The output shows both columns approaching 120 mA, with about 63.2% of the final value at 1 tau. Because the RL and RC loops are the same, one function can serve both circuits. Pass in the initial value, final value, and tau.
A general-purpose checker
Because every first-order transient has the form dx/dt = (x_final - x)/tau, you can write one checker for the whole tutorial. Use it to test a switching problem where the final value and tau change at a switching time.
import math
def euler_segment(x0, x_final, tau, duration, dt):
steps = round(duration / dt)
x = x0
for _ in range(steps):
x += dt * (x_final - x) / tau
return x
def exact_segment(x0, x_final, tau, duration):
return x_final + (x0 - x_final) * math.exp(-duration / tau)
# Capacitor charges toward 10 V with tau = 2 ms for 3 ms,
# then discharges toward 0 V with tau = 5 ms for 10 ms.
v1_euler = euler_segment(0.0, 10.0, 2e-3, 3e-3, 1e-5)
v1_exact = exact_segment(0.0, 10.0, 2e-3, 3e-3)
v2_euler = euler_segment(v1_euler, 0.0, 5e-3, 10e-3, 1e-5)
v2_exact = exact_segment(v1_exact, 0.0, 5e-3, 10e-3)
print(f"After switch 1: Euler {v1_euler:.4f} V, exact {v1_exact:.4f} V")
print(f"After switch 2: Euler {v2_euler:.4f} V, exact {v2_exact:.4f} V")The key step is that the value at the end of one segment becomes the initial value of the next. This applies the continuity rule: capacitor voltage and inductor current cannot jump at a switching event. If you forget this and restart from zero, the simulation will disagree with a correct analytic answer, and the mismatch will point to the mistake.
Common errors the simulation catches
- Wrong resistance in tau. The simulation uses the tau you give it, so a wrong tau still produces a clean exponential. To catch this, compute tau separately from the circuit and compare the simulated time to reach 63.2% with your tau.
- Wrong final value. If the curve settles at a different level than your formula predicts, recheck the circuit at steady state, where the capacitor is open and the inductor is a short.
- Wrong initial value. A jump at t = 0 means you used a value that violates continuity.
- Step too large. A visible gap between Euler and exact at all times, or oscillation, means dt is too large.
Limits of forward Euler
Forward Euler is a good teaching tool for first-order circuits, but it has limits:
- It accumulates error over long runs, so very long simulations need smaller steps.
- It can be unstable for stiff circuits, where one time constant is much smaller than another.
- It is only first-order accurate. Circuit simulators such as SPICE use more accurate and more stable methods, such as trapezoidal integration and backward Euler with adaptive step sizes.
For checking a single-time-constant circuit by hand, Euler with dt = tau/100 is more than adequate.
Exercise
An RL circuit has R = 50 ohms, L = 25 mH, and a 10 V step, with the inductor current starting at zero. Find tau and the final current. Then say what dt you would choose for a forward Euler check, and how many steps you would need to simulate 5 tau.
Show answer
tau = L/R = 25e-3 / 50 = 0.5 ms. The final current is V/R = 10/50 = 0.2 A, or 200 mA. Choosing dt = tau/100 = 5 microseconds gives 100 steps per time constant, so simulating 5 tau needs 500 steps. At 5 tau the exact current is 0.2(1 - e^-5) ≈ 0.1987 A, and the Euler result should agree within about 1 mA or better.
Exercise
In the switching example above, a student restarts the second segment from 0 V instead of from the value reached at the end of the first segment. The capacitor discharges toward 0 V, so what result would the student get for the second segment, and which rule did the student violate?
Show answer
Starting from 0 V and discharging toward 0 V, the simulated voltage stays at 0 V for the whole segment. This is wrong, because the capacitor voltage at the end of the first segment is about 10(1 - e^-1.5) ≈ 7.77 V. The student violated the continuity rule: capacitor voltage cannot change instantly at a switching event, so the final value of one segment is the initial value of the next.