""" Exercise E.24 from "A primer on...". Write a test function for the forward Euler function, based on an ODE system where we know the solution is linear. In this case the solution produced by forward Euler and other numerical methods reproduces the solution to machine precision (no numerical error). """ import numpy as np import matplotlib.pyplot as plt def forward_euler(f, u0, T, N): """Solve u'=f(u,t), u(0)=U0, with n steps until t=T.""" t = np.zeros(N + 1) if np.isscalar(u0): u = np.zeros(N + 1) # u[n] is the solution at time t[n] else: u = np.zeros((N + 1, len(u0))) u[0] = u0 dt = T / N for n in range(N): t[n + 1] = t[n] + dt u[n + 1] = u[n] + dt * f(t[n], u[n]) return t, u def test_forward_euler(): def f(t, u): v, w = u dv = 3 + (3 + 4 * t - w)**3 dw = 4 + (2 + 3 * t - v)**4 return np.array([dv, dw]) tol = 1e-9 T = 5 N = 10 expected = [2 + 3 * T, 3 + 4 * T] t, u = forward_euler(f, [2, 3], T, N) computed = u[-1] assert abs(computed[0] - expected[0]) < tol assert abs(computed[1] - expected[1]) < tol test_forward_euler()