Today we talked about Runge-Kutta methods for approximating solutions of first order ODEs.
\[\frac{dy}{dt} = f(t,y) ~~~ \text{ for } ~ t \in [a,b] ~~~ \text{ with initial condition } ~ y(a) = y_0.\]
The first idea is that you can get a better approximation than Euler’s method using higher degree Taylor polynomials to find \(\Delta y\) at each step. This approach is called the higher order Taylor method for differential equations. We wrote the equation for the second order method:
\[y(t_{i+1}) \approx y(t_i) + y'(t_i) h + \frac{1}{2} y''(t_i) h^2\] which is the same as
\[y(t_{i+1}) \approx y(t_i) + f(t_i,y(t_i)) h + \frac{1}{2} [f_t(t_i,y_i) + f_y(t_i,y_i) f(t_i,y_i)] h^2\] where \(f_t\) and \(f_y\) denote the two partial derivatives of \(f\) that come from using the chain rule for multivariable functions. The problem with this formula is that it requires calculating partial derivatives of \(f\), which is not always feasible. The Runge-Kutta method looks for relatively simple formulas involving \(f(t,y)\) that approximate this expression above without calculating the partial derivatives. The 2nd order Runge-Kutta method known as the midpoint method has this formula
\[y(t_{i+1}) \approx y(t_i) + f(t_i + \tfrac{1}{2}h ,y(t_i) + \tfrac{1}{2}h f(t_i,y_i)) h.\]
The alogrithm to use this formula is:
In class, we implemented the algorithm for this Runge-Kutta method in Python. Then we used it to approximate the solution of this IVP:
We also compared our result with the actual solution \(y(t) = \tfrac{1}{5} t e^{3t} - \tfrac{1}{25} e^{3t} + \tfrac{1}{25} e^{-2t}\) and with the Euler’s method approximate solution. My version of the code for this algorithm is below.
import numpy as np
import matplotlib.pyplot as plt
def RungeKutta2(f,a,b,n,y0):
# Return two lists, one of y-values and the other of t-values
h = (b-a)/n
t, y = a, y0
tvals, yvals = [], []
for i in range(n+1):
tvals.append(t)
yvals.append(y)
y += f(t+h/2,y+h/2*f(t,y))*h
t += h
return tvals, yvalsToday we did this lab on the fourth-order Runge-Kutta method: