""" Ex. E.21 from "A primer on..." Implement the Runge-Kutta 4 method based on the ForwardEuler function introduced earlier. Most of the code in the two functions will be identical, with the only difference being the update formula inside the for-loop. """ import numpy as np import matplotlib.pyplot as plt def ForwardEuler(f, U0, T, N): """Løs u'=f(t,u), u(0)=U0, med N steg til t=T.""" t = np.zeros(N+1) u = np.zeros(N+1) # u[k] er løsningen ved tid t[k] u[0] = U0 t[0] = 0 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 RK4(f, U0, T, N): """Løs u'=f(t,u), u(0)=U0, med N steg til t=T.""" t = np.zeros(N+1) u = np.zeros(N+1) # u[k] er løsningen ved tid t[k] u[0] = U0 t[0] = 0 dt = T / N for n in range(N): t[n+1] = t[n] + dt 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) u[n+1] = u[n] + dt / 6 * (k1 + 2* k2+2*k3+k4) return t, u #solve the problem u' = u def f(t, u): return u U0 = 1 T = 4 N = 10 t, u = ForwardEuler(f, U0, T, N) t2, u2 = RK4(f, U0, T, N) plt.plot(t, u, label = f'euler') plt.plot(t2, u2, label = f'RK4') plt.plot(t, np.exp(t), label = 'exact') plt.legend() plt.show()