Menu Close

Runge-Kutta 2nd Order Method | Python

The Runge-Kutta 2nd order method, also known as the Heun’s method, is a numerical technique used to solve ordinary differential equations (ODEs).

The method uses a combination of the current solution estimate and the derivative at that point to calculate the next solution estimate.

Here is a code of a Python function that implements the Runge-Kutta 2nd order method for a given ODE:

 

Runge-Kutta 2nd Order Method in Python

				
					import math

def rk2_solver(f, y0, t0, tf, h):
    
    # Runge-Kutta 2nd Order Method [By Bottom Science]
    
    t = t0
    y = y0
    while t <= tf:
        k1 = h * f(t, y)
        k2 = h * f(t + h, y + k1)
        y = y + (k1 + k2) / 2
        t = t + h
    return y

def f(t, y):
    return math.sin(t) - y

y0 = 0
t0 = 0
tf = 10
h = 0.1

y_sol = rk2_solver(f, y0, t0, tf, h)

print("Solution at t = ", tf, " is: ", y_sol)

#OUTPUT - Solution at t =  10  is:  0.07700175857290825
				
			

More Related Stuff