""" Ex. E.22 from "A primer on..." Implement the Runge-Kutta 4 method based on the ForwardEuler class introduced earlier. We can create the RK4 class as a subclass of ForwardEuler, and only override the advance-method. All other code is common to the two methods. This solution works for the practical purpose of minimizing code duplication, but conceptually it brakes one of the principles of OOP. It is usually expected that a subclass is a special case of its baseclass, but the Runge-Kutta 4 method is not really a special case of forward Euler. Conceptually, the better solution is to implement a general ODESolver baseclass with all the shared code, and let all the methods be subclasses of this. """ import matplotlib.pyplot as plt import numpy as np class ForwardEuler: def __init__(self, f): self.f = f def solve(self, u0, t_span, N): t0, T = t_span self.dt = (T - t0) / N self.t = np.zeros(N + 1) self.u = np.zeros(N + 1) self.t[0] = t0 self.u[0] = u0 for n in range(N): self.n = n self.t[n + 1] = self.t[n] + self.dt self.u[n + 1] = self.advance() return self.t, self.u def advance(self): """Advance the solution one time step.""" u, dt, f, n, t = self.u, self.dt, self.f, self.n, self.t return u[n] + dt * f(t[n], u[n]) class RK4(ForwardEuler): def advance(self): u, dt, f, n, t = self.u, self.dt, self.f, self.n, self.t k1 = f(t[n], u[n]) k2 = f(t[n] + 0.5 * dt, u[n] + dt * 0.5 * k1) k3 = f(t[n] + 0.5 * dt, u[n] + dt * 0.5 * k2) k4 = f(t[n] + dt, u[n] + dt * k3) return u[n] + dt / 6 * (k1 + 2* k2 + 2 * k3 + k4) class Logistic: def __init__(self, alpha, R): self.alpha, self.R = alpha, R def __call__(self, t, u): return self.alpha * u * (1 - u / self.R) problem = Logistic(alpha=0.2, R=1.0) solver = RK4(problem) print(isinstance(solver, ForwardEuler)) u0 = 0.1 T = 40 t, u = solver.solve(u0, t_span=(0, T), N=400) plt.plot(t, u) plt.title('Logistic growth, Forward Euler') plt.xlabel('t') plt.ylabel('u') plt.show()