Sub topic 15
Simulating Oscillators in Code
Assume you know Newton’s second law, basic derivatives, and the simple harmonic motion equation
\(a = -\omega^2 x\).
This chapter shows how to simulate a spring oscillator numerically and compare it with the exact solution. A numerical simulation calculates the motion in small time steps instead of using a formula for every time.
From the equation to an algorithm
For a mass \(m\) attached to a spring with spring constant \(k\), Hooke’s law gives
\[ F = -kx. \]
Using \(F = ma\),
\[ a = -\frac{k}{m}x. \]
At each time step, the program knows the position \(x\) and velocity \(v\). It calculates the acceleration, updates the velocity, and then updates the position:
\[ v_{\text{new}} = v + a\Delta t \]
\[ x{\text{new}} = x + v{\text{new}}\Delta t. \]
This order is called semi-implicit Euler integration. It is usually more stable for oscillators than updating the position with the old velocity.
A complete spring simulation
The exact solution for an oscillator released from rest at \(x=A\) is
\[ x(t) = A\cos(\omega t), \qquad \omega = \sqrt{\frac{k}{m}}. \]
The program below simulates one second and compares the numerical position with this exact value.
import math
k, m = 20.0, 0.5
x, v = 0.10, 0.0 # start at rest, displaced 0.10 m
dt = 0.001
steps = 1000 # simulate 1 second
for _ in range(steps):
a = -(k / m) * x
v += a * dt # update velocity first (semi-implicit Euler)
x += v * dt
t = steps * dt
analytic = 0.10 * math.cos(math.sqrt(k / m) * t)
print(f"numerical x = {x:.4f} m, analytic x = {analytic:.4f} m")The two results should be close. They are not identical because the numerical method replaces continuous motion with discrete steps.
Choosing the time step
The time step \(\Delta t\) controls both accuracy and cost.
| Time step | Usual effect |
|---|---|
| Small \(\Delta t\) | More calculations and better accuracy |
| Large \(\Delta t\) | Fewer calculations and larger numerical error |
A useful rule is to make \(\Delta t\) much smaller than the period \(T\). For this system,
\[ T = \frac{2\pi}{\omega} = 2\pi\sqrt{\frac{m}{k}}. \]
If the time step is too large, the simulated amplitude may drift, the period may be wrong, or the motion may become unstable.
The same method works for a pendulum after replacing the acceleration model. For small angles, use \(a_\theta = -(g/L)\theta\). For larger angles, use the nonlinear expression involving \(\sin\theta\), so the simulated motion no longer follows exact SHM.
Exercise
What should happen to the numerical result when dt is changed from 0.001 to 0.0001?
Show answer
The result should usually move closer to the analytic solution, because the smaller time step reduces discretization error.