# Python evaluating a second order ODE with RK4

Pasted below is my python code. It is a 4th order runge kutta that evaluates the 2nd order ode: y'' +4y'+2y=0 with initial conditions y(0)=1, y'(0)=3.

I need help fixing it. When I run my code, my analytical solution does not match my numerical solution, my professor said they should be the same. I have tried editing this a bunch and cannot seem to figure out what's wrong. If anyone could review my code and let me know if there is something wrong that would be great. Thank you!

import numpy as np
import matplotlib.pyplot as plt

def ode(y):
return np.array([y,(-2*y-4*y)])

tStart=0

tEnd=5

h=.1

t=np.arange(tStart,tEnd+h,h)

y=np.zeros((len(t),2))

y[0,:]=[1,3]

for i in range(1,len(t)):
k1=ode(y[i-1,:])
k2=ode(y[i-1,:]+h*k1/2)
k3=ode(y[i-1,:]+h*k2/2)
k4=ode(y[i-1,:]+h*k3)

y[i,:]=y[i-1,:]+(h/6)*(k1+2*k3+2*k3+k4)

plt.plot(t,y[:,0])
plt.plot(t,1-t)
plt.grid()
plt.gca().legend(('y(t)',"y'(t)"))
plt.show()
$$$$
`
• Your update is not in the for-loop body
– VoB
Oct 26 '20 at 8:50
• One suggestion: to debug a relatively complex algorithm like RK4 it is usually a good idea to simplify the algorithm to something very basic, like RK1, and see if that works. Oct 27 '20 at 5:38
• Cross-post to stackoverflow.com/questions/64529228/… with my answer guessing that the exact solution that is compared against is not for the given IVP. A freshly computed exact solution matches the numerical solution (with corrected indentation) perfectly. Oct 27 '20 at 20:20