Search code examples
pythontypeerrorodenumerical-integrationrunge-kutta

Runge Kutta 4 Implementation


I am trying to implement the Runge-Kutta Method of order 4. I get a Type Error: 'can't multiply sequence by non-int of type 'numpy.float64' in the calculations of k1,k2,k3,k4. Does anyone know a workaround?

def rk4(f, Y0, t0, tf, n):
    t = np.linspace(t0, tf, n+1)
    Y = np.array([Y0]*(n+1))
    h = t[1]-t[0]
    for i in range(n):
        k1 = h * f(Y[i], t[i])
        k2 = h * f(Y[i]+0.5*k1, t[i]+0.5*h)
        k3 = h * f(Y[i]+0.5*k2, t[i]+0.5*h)
        k4 = h * f(Y[i]+k3, t[i]+h)
        Y[i+1]  = Y[i] + (k1+2*(k2+k3)+k4)/6.0

    return Y, t

Solution

  • You do not return an numpy array from your function f. A list can only be "multiplied" by an integer and produces repetitions by copies of the list, not what you would expect as vector multiplication.

    You can solve this directly in that function by wrapping the return values in a numpy array, or by providing a wrapper

    def rk4(f, Y0, t0, tf, n):
        func = lambda Y,t: np.array(f(Y,t))
        ...
        for i in range(n):
            k1 = h * func(Y[i], t[i])
            ...