TExcelTAD
Home › Differential Equations › Differential Equations Exercises

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 h=0.1h = 0.1 on y′=−2tyy' = -2ty, y(0)=1y(0) = 1. Compare y(1)y(1) with the exact value e−1e^{-1}.

python · try it yourself
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:

text
y(1) = 0.36788107, exact 0.36787944, error 1.6e-06
Solution
python · try it yourself
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 mx′′+cx′+kx=0mx'' + cx' + kx = 0, compute the characteristic roots and print "overdamped", "critically damped" or "underdamped" (Mechanical Vibrations).

python · try it yourself
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:

text
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
Solution
python · try it yourself
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 x′=Ax\mathbf{x}' = A\mathbf{x}, x(0)=(1,0,0)\mathbf{x}(0) = (1, 0, 0) with x(t)=VeΛtV−1x(0)\mathbf{x}(t) = V e^{\Lambda t} V^{-1}\mathbf{x}(0) (The Eigenvalue Method) and check it against scipy.linalg.expm at t=1t = 1.

python · try it yourself
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:

text
eigen: [0.21506  0.185179 0.079725]
expm:  [0.21506  0.185179 0.079725]
Solution

AA is symmetric, so eigh returns an orthogonal VV and V−1=VTV^{-1} = V^T.

python · try it yourself
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 y′′+4y=u(t−1)y'' + 4y = u(t - 1), y(0)=y′(0)=0y(0) = y'(0) = 0 with the Laplace transform (Step Functions and Shifting): find Y(s)Y(s), invert it and evaluate y(2)y(2).

python · try it yourself
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:

text
y(t) = -cos(2*t - 2)*Heaviside(t - 1)/4 + Heaviside(t - 1)/4
y(2) = 0.354037
Solution

Transforming: (s2+4)Y=e−ss(s^2 + 4)Y = \frac{e^{-s}}{s}. Since 1s(s2+4)↔14(1−cos⁡2t)\frac{1}{s(s^2 + 4)} \leftrightarrow \frac{1}{4}(1 - \cos 2t), y=14(1−cos⁡2(t−1))u(t−1)y = \frac{1}{4}\big(1 - \cos 2(t - 1)\big)u(t - 1) and y(2)=1−cos⁡24y(2) = \frac{1 - \cos 2}{4}.

python · try it yourself
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 y′′+xy′+y=0y'' + xy' + y = 0, y(0)=1y(0) = 1, y′(0)=0y'(0) = 0, the series recurrence is ak+2=−akk+2a_{k+2} = -\frac{a_k}{k + 2} (Series Solutions at Ordinary Points). Compute the first coefficients and compare the sum at x=1x = 1 with e−x2/2e^{-x^2/2}.

python · try it yourself
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:

text
['1', '0', '-1/2', '0', '1/8', '0', '-1/48', '0', '1/384']
series at 1: 0.6065306595, exp(-1/2) = 0.6065306597
Solution
python · try it yourself
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 (−1/2)nn!\frac{(-1/2)^n}{n!}, the series of e−x2/2e^{-x^2/2}.

Exercise 6: Cooling rod

A rod of length 1 with k=0.05k = 0.05 has its ends held at 0 and starts at u(x,0)=x(1−x)u(x, 0) = x(1 - x). Using the sine series coefficients bn=8π3n3b_n = \frac{8}{\pi^3n^3} for odd nn (0 for even nn), compute the centre temperature at t=0t = 0, 1 and 5 (The Heat Equation).

python · try it yourself
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:

text
t = 0.0: u(0.5) = 0.250000
t = 1.0: u(0.5) = 0.157403
t = 5.0: u(0.5) = 0.021881
Solution
python · try it yourself
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 t=0t = 0 the series gives 0.5⋅0.5=0.250.5 \cdot 0.5 = 0.25; later the first mode dominates and decays like e−0.05π2te^{-0.05\pi^2t}.

Exercise 7: Classify the equilibria

The damped pendulum θ′=ω\theta' = \omega, ω′=−sin⁡θ−0.3ω\omega' = -\sin\theta - 0.3\omega has equilibria at (0,0)(0, 0) and (π,0)(\pi, 0). Compute the Jacobian at each and classify them (Stability and Classification).

python · try it yourself
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:

text
theta = 0.0000: eigenvalues [-0.15+0.9887j -0.15-0.9887j]
theta = 3.1416: eigenvalues [ 0.8612 -1.1612]
Solution
python · try it yourself
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 R0=2.5R_0 = 2.5 (Epidemic Models: SIR), solve the final-size equation 1−z=e−R0z1 - z = e^{-R_0z} and compare with a simulation.

python · try it yourself
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:

text
final-size equation: 0.8926, simulation: 0.8926
Solution
python · try it yourself
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…

  1. 2
  2. 4
  3. 16
  4. it does not change

A spring with m=2m = 2, c=8c = 8, k=8k = 8 is…

  1. underdamped
  2. critically damped
  3. overdamped
  4. undamped

The upside-down equilibrium of a damped pendulum is…

  1. a spiral sink
  2. a center
  3. a saddle
  4. a stable node