소소한 일상 기록

These days, I tried to make a numerical anlysis function for the 4th-order Runge-Kutta method. I could use ODE function in the Scipy or other public libraries, but I wanted to make it and custumize it.

Here is the python code. I refered to someone else's code and textbook.

import numpy as np


def RK4thOrder(func, yinit, x_range, h):
    n = int((x_range[-1] - x_range[0])/h)
    
    x, y = x_range[0], yinit
    
    del x_range
    
    # Containers for solutions
    xsol, ysol = [x,], [y,]

    i = 0
    while i < n:
        k1 = func(x, y)

        yp2 = y + k1 * h / 2

        k2 = func(x+h/2, yp2)

        yp3 = y + k2 * h / 2

        k3 = func(x+h/2, yp3)

        yp4 = y + k3 * h

        k4 = func(x+h, yp4)

        y = y + (((k1 + k4) + (2 * (k2 + k3))) / 6 * h)
        del k1, k2, k3, k4, yp2, yp3, yp4
        x = x + h
        xsol.append(x)
        ysol.append([])
        i = i + 1
        ysol[i] = y
    ysol = np.array(ysol)
    return xsol, ysol

input value:

  • func: function of differential equation.
  • yinit: inital y value at x[0]. yinit can be 1-dimensional numpy array.
  • x_range: [x_min, x_max]
  • h: interval for an iteration step.

output value:

  • xsol: list of x
  • ysol: numpy array of y
List of Articles
Science and Technology SNI 차단? HTTPS 차단? DNS 차단? 그게 뭐야? 1 2019.02.14 139
Science and Technology Python function for the Runge-Kutta 4th Order Method 2018.10.24 105
Science and Technology 한국형발사체 성공을 빕니다. 2018.08.29 157
Science and Technology jQuery CDN 서비스 제공자들 어디를 쓰는 것이 좋을까? 2018.06.03 376
Science and Technology 패킷 훔쳐보는 정부?... 그렇게 하지 않아도 되지 않나요? 2018.05.12 305
Requesting to the server, please wait.