Home > Python > Ordinary Differential Equation-2

Ch. 12.3 1st Order ODE (RK4 Method)

Chapters Index
Program 1

1st Order ODE (RK4 Method)

Python 3.11 Ready

                                
Click "Run Code" to execute script and render figures.

Mathematical Problem Formulation

An object in free fall under the influence of gravity, with constant acceleration: \(a = 9.81 \, \text{m/s}^2\)

$$ \frac{dv}{dt}=a ;\quad v(t=0)=0 $$

The following code implements the Runge-Kutta 4th order (RK4) method to calculate the velocity of the object over a time period.

Theoretical Background & Explanation

Runge-Kutta 4th Order (RK4) Method

The RK4 method is applied to a differential equation of the form:

$$ \frac{dy}{dt} = f(t, y) $$

with an initial condition \( y(t_0) = y_0 \) over a time interval \([t_0, t_{\text{end}}]\). The method proceeds as follows:

Steps of RK4

For each time step \( h \), the RK4 method calculates four slopes:

  1. Compute \( k_1 \): This is the initial slope, calculated at the beginning of the interval.

    $$ k_1 = f(t, y) $$

  2. Compute \( k_2 \): This slope is calculated at the midpoint, using \( k_1 \) to approximate the halfway position.

    $$ k_2 = f\left(t + \frac{h}{2}, y + \frac{h}{2} \cdot k_1\right) $$

  3. Compute \( k_3 \): Similar to \( k_2 \), but uses the slope from \( k_2 \) to further refine the midpoint estimate.

    $$ k_3 = f\left(t + \frac{h}{2}, y + \frac{h}{2} \cdot k_2\right) $$

  4. Compute \( k_4 \): This final slope is calculated at the end of the interval.

    $$ k_4 = f(t + h, y + h \cdot k_3) $$

Update Rule

The next value, \( y_{\text{next}} \), is computed as a weighted average of these slopes:

$$ y_{\text{next}} = y + \frac{h}{6} \cdot (k_1 + 2 \cdot k_2 + 2 \cdot k_3 + k_4) $$