""" This version of the ODESolver class hierarchy works both for scalar ODEs and systems of ODEs. The dimension of the system is determine by the dimensions of u0 and the right hand side function f(t, u). For instance, for a system of two ODEs, the argument u to f must have length 2, f must return an array or list of length 2, and u0 must have length 2. """ import numpy as np class ODESolver: def __init__(self, f): # Pakk inn brukerens f i en ny funksjon som alltid # konverterer liste/tuple til array (eller lar array være array) self.f = lambda t, u: np.asarray(f(t, u), float) def set_initial_condition(self, u0): if np.isscalar(u0): # scalar ODE self.neq = 1 # no of equations u0 = float(u0) else: # system of ODEs u0 = np.asarray(u0) self.neq = u0.size # no of equations self.u0 = u0 def solve(self, t_span, N): t0, T = t_span self.dt = (T - t0) / N self.t = np.zeros(N + 1) # N steps ~ N+1 time points if self.neq == 1: self.u = np.zeros(N + 1) else: self.u = np.zeros((N + 1, self.neq)) self.t[0] = t0 self.u[0] = self.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 class ForwardEuler(ODESolver): def advance(self): u, f = self.u, self.f n, t, dt = self.n, self.t, self.dt unew = u[n] + dt * f(t[n], u[n]) return unew class ExplicitMidpoint(ODESolver): def advance(self): u, f = self.u, self.f n, t, dt = self.n, self.t, self.dt k1 = f(t[n], u[n]) k2 = f(t[n] + 0.5 * dt, u[n] + 0.5 * dt * k1) return u[n] + dt * k2 class Heun(ODESolver): def advance(self): u, f = self.u, self.f n, t, dt = self.n, self.t, self.dt k1 = f(t[n], u[n]) k2 = f(t[n] + dt, u[n] + dt * k1) return u[n] + 0.5 * dt * (k1 + k2) if __name__ == "__main__": import matplotlib.pyplot as plt 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) euler = ForwardEuler(problem) midpoint = ExplicitMidpoint(problem) u0 = 0.1 T = 40 euler.set_initial_condition(u0) midpoint.set_initial_condition(u0) t1, u1 = euler.solve(t_span=(0, T), N=40) t2, u2 = midpoint.solve(t_span=(0, T), N=40) plt.plot(t1, u1, label = 'Forward Euler') plt.plot(t2, u2, label = 'Midpoint') plt.title('Logistic growth') plt.legend() plt.xlabel('t') plt.ylabel('u') plt.show()