Differential Equations Exercises
Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Solve on paper first, then let the code confirm it. When a numerical result disagrees with your formula, test the formula by substituting it into the equation.
| # | Exercise | Practises |
|---|---|---|
| 1 | An RK4 step | numerical methods, order of accuracy |
| 2 | Classify the damping | characteristic equation, vibrations |
| 3 | Solve a system by eigenvectors | eigenvalue method, matrix exponential |
| 4 | A switched-on force | Laplace transform, step functions |
| 5 | A series solution | power series, recurrences |
| 6 | Cooling rod | heat equation, Fourier sine series |
| 7 | Classify the equilibria | linearization, stability |
| 8 | Epidemic final size | SIR model, separable equations |
Exercise 1: An RK4 step
Implement one step of the classical Runge-Kutta method (Euler's Method) and use it with on , . Compare with the exact value .
import math
def rk4_step(f, t, y, h):
return y + h * f(t, y) # TODO: replace this Euler step by the RK4 formula
f = lambda t, y: -2 * t * y
t, y, h = 0.0, 1.0, 0.1
for _ in range(10):
y = rk4_step(f, t, y, h); t += h
print(f"y(1) = {y:.8f}, exact {math.exp(-1):.8f}, error {abs(y - math.exp(-1)):.1e}")y(1) = 0.38170668, exact 0.36787944, error 1.4e-02
Expected output when solved:
y(1) = 0.36788107, exact 0.36787944, error 1.6e-06Solution
import math
def rk4_step(f, t, y, h):
k1 = f(t, y)
k2 = f(t + h / 2, y + h / 2 * k1)
k3 = f(t + h / 2, y + h / 2 * k2)
k4 = f(t + h, y + h * k3)
return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
f = lambda t, y: -2 * t * y
t, y, h = 0.0, 1.0, 0.1
for _ in range(10):
y = rk4_step(f, t, y, h); t += h
print(f"y(1) = {y:.8f}, exact {math.exp(-1):.8f}, error {abs(y - math.exp(-1)):.1e}")y(1) = 0.36788107, exact 0.36787944, error 1.6e-06
Exercise 2: Classify the damping
For each spring , compute the characteristic roots and print "overdamped", "critically damped" or "underdamped" (Mechanical Vibrations).
import numpy as np
springs = [(1.0, 2.0, 5.0), (2.0, 8.0, 8.0), (1.0, 5.0, 4.0)]
for m, c, k in springs:
roots = np.roots([m, c, k])
kind = "TODO" # TODO: decide from the discriminant c^2 - 4mk
print(f"m={m}, c={c}, k={k}: roots {np.round(roots, 3)} -> {kind}")m=1.0, c=2.0, k=5.0: roots [-1.+2.j -1.-2.j] -> TODO
m=2.0, c=8.0, k=8.0: roots [-2. -2.] -> TODO
m=1.0, c=5.0, k=4.0: roots [-4. -1.] -> TODO
Expected output when solved:
m=1.0, c=2.0, k=5.0: roots [-1.+2.j -1.-2.j] -> underdamped
m=2.0, c=8.0, k=8.0: roots [-2. -2.] -> critically damped
m=1.0, c=5.0, k=4.0: roots [-4. -1.] -> overdampedSolution
import numpy as np
springs = [(1.0, 2.0, 5.0), (2.0, 8.0, 8.0), (1.0, 5.0, 4.0)]
for m, c, k in springs:
roots = np.roots([m, c, k])
disc = c * c - 4 * m * k
kind = "overdamped" if disc > 0 else ("critically damped" if disc == 0 else "underdamped")
print(f"m={m}, c={c}, k={k}: roots {np.round(roots, 3)} -> {kind}")m=1.0, c=2.0, k=5.0: roots [-1.+2.j -1.-2.j] -> underdamped
m=2.0, c=8.0, k=8.0: roots [-2. -2.] -> critically damped
m=1.0, c=5.0, k=4.0: roots [-4. -1.] -> overdamped
Compare the discriminant with 0 exactly only because the inputs are exact here; with measured data use a tolerance.
Exercise 3: Solve a system by eigenvectors
Solve , with (The Eigenvalue Method) and check it against scipy.linalg.expm at .
import numpy as np
from scipy.linalg import expm
A = np.array([[-2.0, 1.0, 0.0], [1.0, -2.0, 1.0], [0.0, 1.0, -2.0]])
x0 = np.array([1.0, 0.0, 0.0])
lam, V = np.linalg.eigh(A)
x_eig = np.zeros(3) # TODO: V @ (exp(lam t) * (V^{-1} x0)) at t = 1
print("eigen:", np.round(x_eig, 6))
print("expm: ", np.round(expm(A) @ x0, 6))eigen: [0. 0. 0.]
expm: [0.21506 0.185179 0.079725]
Expected output when solved:
eigen: [0.21506 0.185179 0.079725]
expm: [0.21506 0.185179 0.079725]Solution
is symmetric, so eigh returns an orthogonal and .
import numpy as np
from scipy.linalg import expm
A = np.array([[-2.0, 1.0, 0.0], [1.0, -2.0, 1.0], [0.0, 1.0, -2.0]])
x0 = np.array([1.0, 0.0, 0.0])
lam, V = np.linalg.eigh(A)
x_eig = V @ (np.exp(lam * 1.0) * (V.T @ x0))
print("eigen:", np.round(x_eig, 6))
print("expm: ", np.round(expm(A) @ x0, 6))eigen: [0.21506 0.185179 0.079725]
expm: [0.21506 0.185179 0.079725]
Exercise 4: A switched-on force
Solve , with the Laplace transform (Step Functions and Shifting): find , invert it and evaluate .
import sympy as sp
t, s = sp.symbols("t s", positive=True)
Y = sp.Integer(0) # TODO: Y(s) = e^{-s} / (s (s^2 + 4))
y = sp.inverse_laplace_transform(Y, s, t)
print("y(t) =", y)
print("y(2) =", round(float(y.subs(t, 2)), 6))y(t) = 0
y(2) = 0.0
Expected output when solved:
y(t) = -cos(2*t - 2)*Heaviside(t - 1)/4 + Heaviside(t - 1)/4
y(2) = 0.354037Solution
Transforming: . Since , and .
import sympy as sp
t, s = sp.symbols("t s", positive=True)
Y = sp.exp(-s) / (s * (s**2 + 4))
y = sp.inverse_laplace_transform(Y, s, t)
print("y(t) =", y)
print("y(2) =", round(float(y.subs(t, 2)), 6))y(t) = -cos(2*t - 2)*Heaviside(t - 1)/4 + Heaviside(t - 1)/4
y(2) = 0.354037
Exercise 5: A series solution
For , , , the series recurrence is (Series Solutions at Ordinary Points). Compute the first coefficients and compare the sum at with .
from fractions import Fraction
import math
a = [Fraction(1), Fraction(0)]
for k in range(0, 18):
a.append(Fraction(0)) # TODO: the recurrence a_{k+2} = -a_k / (k + 2)
print([str(c) for c in a[:9]])
print(f"series at 1: {sum(float(c) for c in a):.10f}, exp(-1/2) = {math.exp(-0.5):.10f}")['1', '0', '0', '0', '0', '0', '0', '0', '0']
series at 1: 1.0000000000, exp(-1/2) = 0.6065306597
Expected output when solved:
['1', '0', '-1/2', '0', '1/8', '0', '-1/48', '0', '1/384']
series at 1: 0.6065306595, exp(-1/2) = 0.6065306597Solution
from fractions import Fraction
import math
a = [Fraction(1), Fraction(0)]
for k in range(0, 18):
a.append(-a[k] / (k + 2))
print([str(c) for c in a[:9]])
print(f"series at 1: {sum(float(c) for c in a):.10f}, exp(-1/2) = {math.exp(-0.5):.10f}")['1', '0', '-1/2', '0', '1/8', '0', '-1/48', '0', '1/384']
series at 1: 0.6065306595, exp(-1/2) = 0.6065306597
The even coefficients are , the series of .
Exercise 6: Cooling rod
A rod of length 1 with has its ends held at 0 and starts at . Using the sine series coefficients for odd (0 for even ), compute the centre temperature at , 1 and 5 (The Heat Equation).
import numpy as np
k = 0.05
n = np.arange(1, 200)
b = np.zeros(n.size) # TODO: 8 / (pi^3 n^3) for odd n, 0 for even n
for t in (0.0, 1.0, 5.0):
u = np.sum(b * np.exp(-k * (n * np.pi)**2 * t) * np.sin(n * np.pi * 0.5))
print(f"t = {t}: u(0.5) = {u:.6f}")t = 0.0: u(0.5) = 0.000000
t = 1.0: u(0.5) = 0.000000
t = 5.0: u(0.5) = 0.000000
Expected output when solved:
t = 0.0: u(0.5) = 0.250000
t = 1.0: u(0.5) = 0.157403
t = 5.0: u(0.5) = 0.021881Solution
import numpy as np
k = 0.05
n = np.arange(1, 200)
b = np.where(n % 2 == 1, 8 / (np.pi**3 * n**3), 0.0)
for t in (0.0, 1.0, 5.0):
u = np.sum(b * np.exp(-k * (n * np.pi)**2 * t) * np.sin(n * np.pi * 0.5))
print(f"t = {t}: u(0.5) = {u:.6f}")t = 0.0: u(0.5) = 0.250000
t = 1.0: u(0.5) = 0.157403
t = 5.0: u(0.5) = 0.021881
At the series gives ; later the first mode dominates and decays like .
Exercise 7: Classify the equilibria
The damped pendulum , has equilibria at and . Compute the Jacobian at each and classify them (Stability and Classification).
import numpy as np
def jacobian(theta):
return np.zeros((2, 2)) # TODO: [[0, 1], [-cos(theta), -0.3]]
for theta in (0.0, np.pi):
ev = np.linalg.eigvals(jacobian(theta))
print(f"theta = {theta:.4f}: eigenvalues {np.round(ev, 4)}")theta = 0.0000: eigenvalues [0. 0.]
theta = 3.1416: eigenvalues [0. 0.]
Expected output when solved:
theta = 0.0000: eigenvalues [-0.15+0.9887j -0.15-0.9887j]
theta = 3.1416: eigenvalues [ 0.8612 -1.1612]Solution
import numpy as np
def jacobian(theta):
return np.array([[0.0, 1.0], [-np.cos(theta), -0.3]])
for theta in (0.0, np.pi):
ev = np.linalg.eigvals(jacobian(theta))
print(f"theta = {theta:.4f}: eigenvalues {np.round(ev, 4)}")theta = 0.0000: eigenvalues [-0.15+0.9887j -0.15-0.9887j]
theta = 3.1416: eigenvalues [ 0.8612 -1.1612]
Hanging down: complex eigenvalues with negative real part, a spiral sink. Upside down: real eigenvalues of opposite sign, a saddle.
Exercise 8: Epidemic final size
For an SIR epidemic with (Epidemic Models: SIR), solve the final-size equation and compare with a simulation.
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
R0, gamma, N = 2.5, 0.2, 1e6
z = 0.0 # TODO: brentq on 1 - z - exp(-R0 z) over (1e-9, 1)
beta = R0 * gamma
sol = solve_ivp(lambda t, y: [-beta * y[0] * y[1] / N, beta * y[0] * y[1] / N - gamma * y[1]],
(0, 400), [N - 1, 1], rtol=1e-10, atol=1e-8)
print(f"final-size equation: {z:.4f}, simulation: {1 - sol.y[0][-1] / N:.4f}")final-size equation: 0.0000, simulation: 0.8926
Expected output when solved:
final-size equation: 0.8926, simulation: 0.8926Solution
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
R0, gamma, N = 2.5, 0.2, 1e6
z = brentq(lambda z: 1 - z - np.exp(-R0 * z), 1e-9, 1)
beta = R0 * gamma
sol = solve_ivp(lambda t, y: [-beta * y[0] * y[1] / N, beta * y[0] * y[1] / N - gamma * y[1]],
(0, 400), [N - 1, 1], rtol=1e-10, atol=1e-8)
print(f"final-size equation: {z:.4f}, simulation: {1 - sol.y[0][-1] / N:.4f}")final-size equation: 0.8926, simulation: 0.8926
Test yourself
Halving the step size of RK4 reduces the global error by roughly…
- 2
- 4
- 16
- it does not change
A spring with , , is…
- underdamped
- critically damped
- overdamped
- undamped
The upside-down equilibrium of a damped pendulum is…
- a spiral sink
- a center
- a saddle
- a stable node