""" Example code from lecture 27/10. The forward Euler method implemented as a simple, stand-alone class. This example is not particularly useful in itself, but serves an intro to the implementation that uses a class hierarchy. """ 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 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 = ForwardEuler(problem) 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()