""" Ex E.2 from "A primer on..." Solve the same ODE as in E.1, but this time using the class implementation of the ForwardEuler solver. The main difference of this approach is that we need to create an instance of the solver class and then call this instance's methods to solve the ODE. We also implement the right hand side function as a class. """ 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 SimpleODE: def __init__(self, tau): self.tau = tau def __call__(self, t, u): return self.tau * u problem = SimpleODE(0.1) solver = ForwardEuler(problem) u0 = 0.2 T = 20 N = 4 t, u = solver.solve(u0, (0, T), N) plt.plot(t,u) plt.show()