Why is my fourth order Runge Kutta method not accurate

141 Views Asked by At
def runge_kutta(f, x0, dt, T):
    n = int(T / dt)

    t = np.zeros(n + 1)
    if isinstance(x0, (int, float)):
        x = np.zeros(n + 1)
    else:
        neqns = len(x0)
        x = np.zeros((n + 1, neqns))
    x[0] = x0
    t[0] = 0

    for i in range(n):
        t[i + 1] = t[i] + dt

        k1 = np.dot(dt, f.f(x[i], t[i]))
        k2 = np.dot(dt, f.f(x[i] + 0.5 * k1, t[i] + dt / 2))
        k3 = np.dot(dt, f.f(x[i] + 0.5 * k2, t[i] + dt / 2))
        k4 = np.dot(dt, f.f(x[i] + k3, t[i] + dt))

        x[i + 1] = x[i] + np.dot((1/6), (k1 + 2 * k2 + 3 * k3 + k4))

    return x, t

This is what I wrote for a fourth order Runge Kutta method, but when I test it with a function it showed a high degree of inaccuracy (much higher than what I got for my forward Euler method), which leads me to believe that there is some mistakes in my code. Here is what the Runge Kutta (3 different step sizes, in dotted lines) in action against the exact solutions (solid line) Test Function Results

Could someone help me on what is wrong in my code?