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

限于喜欢 提交于 2021-02-08 02:07:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/52334558/runge-kutta-4th-order-method-to-solve-second-order-odes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!