TExcelTAD
Home › Differential Equations › Differential Equations in Software

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 x′′=F/m\mathbf{x}'' = \mathbf{F}/m. The choice of method matters: plain (explicit) Euler adds energy to oscillations, while semi-implicit (symplectic) Euler keeps it bounded for the same cost.

python · try it yourself
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 x′=−λ(x−target)x' = -\lambda(x - \text{target}) over one frame: a = 1 - exp(-lambda * dt).

python · try it yourself
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 e=target−ye = \text{target} - y and applies u=Kpe+Ki∫e dt+Kde′u = K_pe + K_i\int e\,dt + K_de'. Together with the plant (here a cart with friction, y′′=u−0.5y′y'' = u - 0.5y'), the whole loop is a system of ODEs whose eigenvalues decide stability and overshoot (Transfer Functions and Stability).

python · try it yourself
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 θ′=−∇L(θ)\boldsymbol{\theta}' = -\nabla L(\boldsymbol{\theta}) with step size equal to the learning rate. The step-size limit γ<2λmax⁡\gamma < \frac{2}{\lambda_{\max}} from Gradient Descent is exactly Euler's stability limit from Euler's Method.

A residual network layer hk+1=hk+f(hk)\mathbf{h}_{k+1} = \mathbf{h}_k + f(\mathbf{h}_k) is one Euler step of h′=f(h)\mathbf{h}' = f(\mathbf{h}); neural ODEs take this literally and let an adaptive ODE solver choose the "depth".

python · try it yourself
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 τy′+y=x(t)\tau y' + y = x(t) 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 λ\lambda, and what per-frame factor a should be used at 120 fps?

Answer

λ=ln⁡200.25≈11.98\lambda = \frac{\ln 20}{0.25} \approx 11.98 per second; a=1−e−λ/120≈0.0950a = 1 - e^{-\lambda/120} \approx 0.0950.

Solution

e−0.25λ=0.05e^{-0.25\lambda} = 0.05 gives λ=4ln⁡20\lambda = 4\ln 20. Then a=1−e−λ⋅1120a = 1 - e^{-\lambda \cdot \frac{1}{120}}.

Exercise 2: Residual networks

Which ODE does hk+1=hk+0.1tanh⁡(Whk)\mathbf{h}_{k+1} = \mathbf{h}_k + 0.1\tanh(W\mathbf{h}_k) discretize, and with what step?

Answer

h′=tanh⁡(Wh)\mathbf{h}' = \tanh(W\mathbf{h}) with Euler step 0.1.

Solution

Euler's method for h′=f(h)\mathbf{h}' = f(\mathbf{h}) is hk+1=hk+Δt f(hk)\mathbf{h}_{k+1} = \mathbf{h}_k + \Delta t\,f(\mathbf{h}_k).

Exercise 3: Explicit Euler's energy growth (code)

For the spring x′′=−kxx'' = -kx, explicit Euler multiplies the energy by exactly 1+k Δt21 + k\,\Delta t^2 each step. Check this for k=40k = 40, Δt=160\Delta t = \frac{1}{60} over 600 steps.

Answer

The energy grows by a factor (1+40/3600)600≈757(1 + 40/3600)^{600} \approx 757.

Solution

For xn+1=xn+Δt vnx_{n+1} = x_n + \Delta t\,v_n, vn+1=vn−Δt kxnv_{n+1} = v_n - \Delta t\,kx_n: vn+12+kxn+12=(1+kΔt2)(vn2+kxn2)v_{n+1}^2 + kx_{n+1}^2 = (1 + k\Delta t^2)(v_n^2 + kx_n^2) (expand; the cross terms cancel).

python · try it yourself
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 γ\gamma is which method applied to θ′=−∇L\boldsymbol{\theta}' = -\nabla L?

  1. RK4
  2. Euler's method with step γ\gamma
  3. the matrix exponential
  4. Laplace transform

Why do games prefer semi-implicit Euler to explicit Euler?

  1. It is more accurate in general
  2. It keeps the energy of oscillations bounded at the same cost
  3. It needs no time step
  4. It is implicit and unconditionally stable

Frame-rate independent smoothing toward a target uses the factor…

  1. a fixed 0.1
  2. 1−e−λ Δt1 - e^{-\lambda\,\Delta t}
  3. λ Δt2\lambda\,\Delta t^2
  4. 1/fps1/\text{fps}