Runge-Kutta 4th order method to solve second-order ODES

pmoreira picture pmoreira · Sep 14, 2018 · Viewed 8.2k times · Source

I am trying to do a simple example of the harmonic oscillator, which will be solved by Runge-Kutta 4th order method. The second-order ordinary differential equation (ODE) to be solved and the initial conditions are:

y'' + y = 0

y(0) = 0 and y'(0) = 1/pi

The range is between 0 and 1 and there are 100 steps. I separated my 2nd order ODE in two first-order ODEs, using u as auxiliary variable:

y' = u

u' = -y

The analytical solution is sinusoidal y(x) = (1/pi)^2 sin(pi*x).

My Python code is below:

from math import pi
from numpy import arange
from matplotlib.pyplot import plot, show

# y' = u
# u' = -y

def F(y, u, x):
    return -y

a = 0
b = 1.0
N =100
h = (b-a)/N

xpoints = arange(a,b,h)
ypoints = []
upoints = []

y = 0.0
u = 1./pi 

for x in xpoints:
    ypoints.append(y)
    upoints.append(u)

    m1 = h*u
    k1 = h*F(y, u, x)  #(x, v, t)

    m2 = h*(u + 0.5*k1)
    k2 = h*F(y+0.5*m1, u+0.5*k1, x+0.5*h)

    m3 = h*(u + 0.5*k2)
    k3 = h*F(y+0.5*m2, u+0.5*k2, x+0.5*h)

    m4 = h*(u + k3)
    k4 = h*F(y+m3, u+k3, x+h)

    y += (m1 + 2*m2 + 2*m3 + m4)/6
    u += (k1 + 2*k2 + 2*k3 + k4)/6

plot(xpoints, ypoints)
show()

All code was corrected as suggested by LutzL. See comments below.

The code is running but my numerical solution does not match with the analytical solution. I made a graph showing the two solutions below. I compared my script with some other's codes (https://math.stackexchange.com/questions/721076/help-with-using-the-runge-kutta-4th-order-method-on-a-system-of-2-first-order-od) on internet and I cannot see the error. In the link, there are two codes, a Matlab one and Fortran one. Even then, I cannot find my mistake. Can anyone help me?

enter image description here

Answer

pmoreira picture pmoreira · Sep 17, 2018

My code is correct. The analytical solution was wrong. The correct analytical answer is

sin(x)/pi

as LutzL pointed. Below, one can see the analytical and numerical solutions. The limits are from a=0 to b=6.5.

enter image description here