0

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 + 2 * k3 + k4))

    return x, t

This is my code for a fourth order Runge Kutta method. How can I implement an adaptive stepsize tool that takes in an error e and an initial stepsize dt, and estimates the error in the first term. If the error is less than e, the code uses dt to approximate the solution. And if the error is greater than e, set dt = dt/2 and do the process again.

This is the goal for what the code should do but I have no clue on how to implement it. Could someone tell me how I can do it?

James
  • 1
  • 1
  • See other topics about step-doubling https://stackoverflow.com/questions/67043427/how-to-perform-adaptive-step-size-using-runge-kutta-fourth-order-matlab, https://stackoverflow.com/questions/72164764/step-doubling-runge-kutta-implementation-stuck-shrinking-stepsize-to-machine-pre, and the basic principles demonstrated on the Euler method https://stackoverflow.com/questions/49256309/matlab-euler-explicit-ode-solver-with-adaptable-step-is-there-a-way-to-make-cod, https://math.stackexchange.com/questions/4437080/adaptive-step-size-for-euler-method-how-to-create – Lutz Lehmann Dec 22 '22 at 20:44

0 Answers0