In this lab, you will implement the different Runge-Kutta Methods we studied in class. Please test your implementation on the function given in this webpage. Compare your answers with the ones given below.
from math import *
from matplotlib import pyplot as plt
import numpy as np
import ode_solvers as ode
np.set_printoptions(precision=5, suppress=True)
def ode_euler (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
def ode_rk1 (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
def ode_rk2_heun (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
def ode_rk2_midpoint (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
def ode_rk2_ralston (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
# This is THE Runge-Kutta Method, rk4
def ode_solve (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
def ode_rk4_38 (f, tn, tdelta, x0=0, t0=0) :
return tn, xn
# Use your code to solve the following differential eqn
# dx/dt + 2x = cos(4t) x(0) = 3
# Compare the solutions for different methods.
# The exact solution is
# x(t) = 0.2sin(4t)+0.1cos(4t)+2.9exp(-2t)
xt = np.zeros((51,2))
count = 0
for i in np.linspace(0.0, 10.0, 51) :
xt[count,:] = ode.ode_rk4_16(ode.xdot, i, 0.2, x0=3.)
count = count + 1
print xt[:,1]
def exact (x) :
return 0.2 * sin(4.0 * x) + 0.1 * cos(4.0 * x) + 2.9 * exp(-2.0 * x)
count = 0
xte = np.zeros(51)
for i in np.linspace(0.0, 10.0, 51) :
xte[count] = exact(i)
count = count + 1
print xte
plt.plot(xt[:,0], xt[:,1], 'g-')
plt.plot(xt[:,0], xte, 'b.')
plt.show()