Sub topic 15
Simulating oscillators in code
This chapter assumes you know Newton's second law, the SHM equation a = -ω²x and its solution x(t) = A cos(ωt + φ), the pendulum equation, and energy in SHM. It also assumes you can read basic Python. Here you turn those equations into a program, check it against the analytic answer, and learn which step rules can be trusted.
Why simulate something we can solve
The spring-mass system and the small-angle pendulum have exact solutions, so a simulation adds nothing for them. It earns its place in two other ways:
- It checks the method. If your code reproduces x(t) = A cos(ωt) for the spring, you can trust it on problems with no closed form.
- It handles physics the SHM model drops. The full pendulum equation, damping, and driving have no simple solution, but the same loop works for all of them. You only change the acceleration function.
The idea: step the state forward
An oscillator's state is its position x and velocity v. Newton's second law gives the acceleration from the position alone. For the spring, a = -(k/m)x. Pick a small time step dt and repeat three things:
- Compute a from the current x.
- Update v using a.
- Update x using v.
The order of steps 2 and 3, and which values each step uses, decides whether the simulation is trustworthy.
Three update rules
The loop above leaves open which x and v each update uses. Three common choices:
- Explicit Euler updates both quantities from the old values: x ← x + v·dt, v ← v + a·dt.
- Semi-implicit (symplectic) Euler updates v first, then uses the new v to update x. This is the rule from the earlier example.
- Velocity Verlet uses the average of the old and new acceleration to update v, and a second-order expression for x.
| Method | Accuracy per step | Energy behavior for an oscillator | Cost per step |
|---|---|---|---|
| Explicit Euler | First order | Energy grows steadily, so the amplitude creeps up | One acceleration call |
| Semi-implicit Euler | First order | Energy wobbles slightly but does not drift | One acceleration call |
| Velocity Verlet | Second order | Energy wobbles by a much smaller amount | One acceleration call per step (reuse the stored value) |
The energy column matters most here. An undamped oscillator conserves energy exactly, so any steady drift in your numbers is an error in the method, not physics.
Experiment: which rule keeps energy constant
The program below runs all three rules on the 0.5 kg, 20 N/m spring from earlier chapters. It starts at rest, displaced 0.10 m, and runs for 10 s. It prints the final energy divided by the starting energy.
import math
k, m = 20.0, 0.5
omega2 = k / m
def accel(x):
return -omega2 * x
def explicit_euler(x, v, dt):
a = accel(x)
return x + v * dt, v + a * dt
def semi_implicit(x, v, dt):
v = v + accel(x) * dt
return x + v * dt, v
def velocity_verlet(x, v, dt):
a = accel(x)
x_new = x + v * dt + 0.5 * a * dt * dt
v_new = v + 0.5 * (a + accel(x_new)) * dt
return x_new, v_new
def energy(x, v):
return 0.5 * m * v * v + 0.5 * k * x * x
dt = 0.001
steps = 10000 # 10 seconds
methods = [
("explicit Euler", explicit_euler),
("semi-implicit", semi_implicit),
("velocity Verlet", velocity_verlet),
]
for name, step in methods:
x, v = 0.10, 0.0
e0 = energy(x, v)
for _ in range(steps):
x, v = step(x, v, dt)
print(f"{name:<16} E/E0 = {energy(x, v) / e0:.4f}")Explicit Euler should print a ratio near 1.49. Its energy is multiplied by (1 + ω²dt²) on every step. Here ω²dt² = 40 × 10⁻⁶, so over 10 000 steps the factor is about e^0.4. That is a 49% energy gain from a rule that looks reasonable. The other two ratios should stay close to 1, with Verlet closest.
Compare with the analytic solution
Matching the closed-form answer is the standard test of a simulation. The semi-implicit example from the spring-mass chapter did this at t = 1 s: both values come out near 0.0999 m, because ωt = 6.325 rad is just past one full cycle. A single point can match by luck, so a better check compares the whole trajectory:
import math
k, m = 20.0, 0.5
omega = math.sqrt(k / m)
A = 0.10
dt = 0.001
steps = 5000 # 5 seconds
x, v = A, 0.0
worst = 0.0
for n in range(1, steps + 1):
v += -(k / m) * x * dt # semi-implicit Euler
x += v * dt
exact = A * math.cos(omega * n * dt)
worst = max(worst, abs(x - exact))
print(f"largest position error over 5 s: {worst:.2e} m")The largest error is a small fraction of the 0.10 m amplitude. Try dt = 0.01 and dt = 0.0001. For a first-order method the worst-case error should shrink roughly in proportion to dt. If it does not, suspect a bug.
Choosing dt
A time step must be small compared with the period. A common rule of thumb is dt below T/100, which gives at least 100 steps per cycle. For this spring, T ≈ 0.993 s, so dt = 0.001 s gives nearly 1000 steps per cycle.
Two failure signs to watch for:
- Energy drifts in one direction. The method is wrong for oscillators, as with explicit Euler.
- The result changes noticeably when you halve dt. Your dt is still too large. Keep halving it until the answer stops changing in the digits you care about.
Simulating the full pendulum
Nothing in the loop depends on the force being linear. For a pendulum, swap in the exact angular acceleration α = -(g/L) sin θ. The small-angle approximation is no longer needed. The next program measures the period numerically. It releases the pendulum from rest at θ₀ and finds when θ first crosses zero, which is a quarter period. Linear interpolation between the two steps around the crossing sharpens the time.
import math
def pendulum_period_numeric(theta0, L=1.0, g=9.81, dt=1e-4):
w2 = g / L
th, om = theta0, 0.0
a = -w2 * math.sin(th)
t = 0.0
while True:
th_new = th + om * dt + 0.5 * a * dt * dt
a_new = -w2 * math.sin(th_new)
om_new = om + 0.5 * (a + a_new) * dt
if th_new <= 0.0:
frac = th / (th - th_new)
return 4.0 * (t + frac * dt)
th, om, a, t = th_new, om_new, a_new, t + dt
T0 = 2 * math.pi * math.sqrt(1.0 / 9.81)
for deg in (5, 30, 90):
T = pendulum_period_numeric(math.radians(deg))
print(f"{deg:>3} deg: T = {T:.4f} s, T/T0 = {T / T0:.4f}")The ratios should be about 1.0005, 1.0174, and 1.1803. These match the exact values from the arithmetic-geometric mean formula in the large-amplitude chapter. A 90° swing takes about 2.368 s, compared with 2.006 s for the small-angle formula. A simulation reproduces the anharmonic period lengthening with no extra theory, because the only change from the spring code is the line that computes acceleration.
Common errors
- Using the new x in the wrong place. Semi-implicit Euler must update v first and then use the new v for x. Swapping the two lines gives a different method, which also conserves energy but is easy to confuse with explicit Euler.
- Degrees in math.sin. Python's trig functions take radians. Convert with math.radians.
- Comparing at one instant only. One matching point does not validate the code. Compare the whole trajectory or the energy.
- Mixing units. Use SI units throughout (N/m, kg, m, s), or the period will be wrong by a factor you cannot spot easily.
Exercise
You run the 20 N/m, 0.5 kg spring simulation with explicit Euler and dt = 0.001 s for 10 s and see the energy rise by about 49%. A colleague suggests cutting dt to 0.0001 s. Predict the energy ratio after 10 s with that dt, and say whether it fixes the problem. What would you change instead?
Show answer
With dt = 0.0001, ω²dt² = 40 × 10⁻⁸ = 4 × 10⁻⁷, and there are 100 000 steps. The ratio is about e^(100 000 × 4 × 10⁻⁷) = e^0.04 ≈ 1.04. This is smaller but still a 4% error that grows with run time, so the drift is only slowed and the problem is not fixed. A better fix is to change the rule to semi-implicit Euler or velocity Verlet, which keep the energy bounded at the original dt.