Differential Equations in Software
Differential equations run inside a surprising amount of everyday software: game physics, animation, audio, control loops, machine learning. This lesson gathers the patterns that recur, with a small runnable example of each, and points to where each is treated in depth.
1. Game physics: integrate Newton's law every frame
A game loop advances positions and velocities by a fixed dt each frame, which is a numerical ODE solver for . The choice of method matters: plain (explicit) Euler adds energy to oscillations, while semi-implicit (symplectic) Euler keeps it bounded for the same cost.
import math
k, dt, steps = 40.0, 1 / 60, 600 # a stiff-ish spring, 60 fps, 10 seconds
def energy(x, v): return 0.5 * v * v + 0.5 * k * x * x
for name in ("explicit Euler", "semi-implicit Euler"):
x, v = 1.0, 0.0
for _ in range(steps):
if name == "explicit Euler":
x, v = x + dt * v, v - dt * k * x
else:
v = v - dt * k * x
x = x + dt * v
print(f"{name:20s}: energy after 10 s = {energy(x, v):.4f} (start {energy(1.0, 0.0):.4f})")explicit Euler : energy after 10 s = 15148.1545 (start 20.0000)
semi-implicit Euler : energy after 10 s = 19.2029 (start 20.0000)
More in Game Physics and Long-Time Integration and Symplectic Methods.
2. Smoothing and animation: frame-rate independent decay
Exponential smoothing toward a target, x += (target - x) * a, behaves differently at 30 and 144 fps unless a comes from the exact solution of over one frame: a = 1 - exp(-lambda * dt).
import math
lam, target = 8.0, 10.0
for fps in (30, 60, 144):
dt = 1 / fps
naive, exact = 0.0, 0.0
for _ in range(fps // 2): # half a second
naive += (target - naive) * 0.15 # tuned at 60 fps
exact += (target - exact) * (1 - math.exp(-lam * dt))
print(f"{fps:3d} fps after 0.5 s: naive {naive:.3f}, exact-decay {exact:.3f}") 30 fps after 0.5 s: naive 9.126, exact-decay 9.817
60 fps after 0.5 s: naive 9.924, exact-decay 9.817
144 fps after 0.5 s: naive 10.000, exact-decay 9.817
The exact-decay version reaches the same value at every frame rate.
3. Control: a PID controller closes the loop
A controller measures the error and applies . Together with the plant (here a cart with friction, ), the whole loop is a system of ODEs whose eigenvalues decide stability and overshoot (Transfer Functions and Stability).
import numpy as np
from scipy.integrate import solve_ivp
Kp, Ki, Kd, target = 4.0, 1.0, 2.0, 1.0
def loop(t, s):
y, v, integral = s
e = target - y
u = Kp * e + Ki * integral + Kd * (-v) # derivative of the error is -v
return [v, u - 0.5 * v, e]
sol = solve_ivp(loop, (0, 20), [0, 0, 0], t_eval=np.linspace(0, 20, 2001), rtol=1e-9)
y = sol.y[0]
print(f"overshoot {100 * (y.max() - 1):.1f} %, y(20) = {y[-1]:.4f}")
A = np.array([[0, 1, 0], [-Kp, -0.5 - Kd, Ki], [-1, 0, 0]])
print("closed-loop eigenvalues:", np.round(np.linalg.eigvals(A), 3))overshoot 24.3 %, y(20) = 1.0006
closed-loop eigenvalues: [-1.1 +1.46j -1.1 -1.46j -0.299+0.j ]
4. Machine learning: gradient flow and neural ODEs
Gradient descent is Euler's method for the gradient flow with step size equal to the learning rate. The step-size limit from Gradient Descent is exactly Euler's stability limit from Euler's Method.
A residual network layer is one Euler step of ; neural ODEs take this literally and let an adaptive ODE solver choose the "depth".
import numpy as np
H = np.diag([1.0, 10.0]) # loss L = 0.5 theta^T H theta
theta0 = np.array([1.0, 1.0])
for lr in (0.05, 0.19, 0.21):
th = theta0.copy()
for _ in range(100):
th = th - lr * H @ th # Euler step of theta' = -H theta
print(f"lr = {lr}: |theta| after 100 steps = {np.linalg.norm(th):.3e} (stable iff lr < 2/10 = 0.2)")lr = 0.05: |theta| after 100 steps = 5.921e-03 (stable iff lr < 2/10 = 0.2)
lr = 0.19: |theta| after 100 steps = 2.656e-05 (stable iff lr < 2/10 = 0.2)
lr = 0.21: |theta| after 100 steps = 1.378e+04 (stable iff lr < 2/10 = 0.2)
5. Audio: filters are discretized ODEs
A one-pole low-pass filter is the ODE discretized at the sample rate; resonant filters are discretized damped oscillators. scipy.signal.bilinear converts a continuous transfer function into a digital filter.
Choosing a solver
| Situation | Typical choice |
|---|---|
| real-time game, fixed frame rate | semi-implicit Euler or Verlet |
| accurate non-stiff simulation | adaptive Runge-Kutta (solve_ivp default RK45, DOP853) |
| stiff chemistry, circuits, fast decays | implicit methods (BDF, Radau, LSODA) |
| long orbits, molecular dynamics | symplectic methods |
| linear constant-coefficient | matrix exponential |
The theory behind each choice is in Numerical Methods.
Exercises
Exercise 1: Smoothing factor
A UI value should close 95 % of the gap to its target in 0.25 s. What is , and what per-frame factor a should be used at 120 fps?
Answer
per second; .
Solution
gives . Then .
Exercise 2: Residual networks
Which ODE does discretize, and with what step?
Answer
with Euler step 0.1.
Solution
Euler's method for is .
Exercise 3: Explicit Euler's energy growth (code)
For the spring , explicit Euler multiplies the energy by exactly each step. Check this for , over 600 steps.
Answer
The energy grows by a factor .
Solution
For , : (expand; the cross terms cancel).
k, dt = 40.0, 1 / 60
x, v = 1.0, 0.0
E0 = v * v + k * x * x
for _ in range(600):
x, v = x + dt * v, v - dt * k * x
print(round((v * v + k * x * x) / E0, 3), round((1 + k * dt * dt) ** 600, 3))757.408 757.408
Test yourself
Gradient descent with learning rate is which method applied to ?
- RK4
- Euler's method with step
- the matrix exponential
- Laplace transform
Why do games prefer semi-implicit Euler to explicit Euler?
- It is more accurate in general
- It keeps the energy of oscillations bounded at the same cost
- It needs no time step
- It is implicit and unconditionally stable
Frame-rate independent smoothing toward a target uses the factor…
- a fixed 0.1