Python question:
I have the following RK-4 code that evaluates my first order ode, but I want to edit it such that it can evaluate the following 2nd order ode as a system of first order ODE's: (d^2y/dt^2) +4(dy/dt)+2y=0. I would like to keep h (the step size the same) and the initial conditions would be y(0)=1 and y'(0)=3.
I am very new to python, so I am having a hard time doing this. Thank you in advance for any help!
import matplotlib.pyplot as plt
def dydx(x, y):
return ((x - y)/2)
def rungeKutta(x0, y0, x, h):
n = (int)((x - x0)/h)
y = y0
for i in range(1, n + 1):
k1 = h * dydx(x0, y)
k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1)
k3 = h * dydx(x0 + 0.5 * h, y + 0.5 * k2)
k4 = h * dydx(x0 + h, y + k3)
y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4)
x0 = x0 + h
return y
x0 = 0
y = 1
x = 2
h = 0.2
print ('The value of y at x is:', rungeKutta(x0, y, x, h))
The only change that is necessary is to make the state a vector object. In python this is usually a numpy array. So
Everything else should automatically use the appropriate vector operations.