Runge-kutta method using Python.

My exams finally got over . I got back home and slept for a week continuously . After that I realised I had to solve a differential equation for a project . Seniors told me the Runge-kutta method is numerically the best method to find function values at a particular point provided you are given the differential equation and the initial conditions.

So here is my interpretation of the method .

You are given a function at a given point and you need to find the function value at a point . So you find the function value at a minutely greater point using the Runge-Kutta method and keep iterating till you reach the given point.

Suppose the given differential equation is

\frac{du}{dx} = x ; u(0) = 0 || Comparing it with  \frac{du}{ dx} = f(x)

You need to increment by a really small value , lets say 0.1

The Runge-Kutta method gives us four values of slope , k1k2, k3 and k4 , k1 and k4 are near the two ends of the function ,  k2 and k3 are near the midpoints .

k1 =  f(x , u(x))  = f(0 , 0) = 0
k2 = f(x + delx / 2 ,  u(x) + 0.5k1)  = f(0.05 , 0) = 0.05
k3 = f(x + delx / 2 , u(x) + 0.5k2) = f(0.05 , 0.025) = 0.05

These are approximate slope values at the midpoints.
k4 = f(x + delx , u(x) + k3) = f(0.1 ,  0.05) = 0.1

The A.M of these four values will be (k1 + 2 *(k2 + k3) + k4) / 6 and into delx will give the y increment which gives (1 / 6) * (0 + 2 * (0.05 + 0.05) + 0.1) * 0.1 = 0.005
Which indeed is the function value that can be got by simple-integration , u(x) will be x^2 / 2

Suppose you would like to find the value at some larger point say at x = 100 . Simple , perform a number of iterations using delx = 0.1 till you reach 100 . The smaller the size of increment for each iteration , the better.

This is a simple python code for the case in which f(x) is a simple polynomial

https://github.com/Manoj-Kumar-S/Rk4-Polynomials/blob/master/rk4.py

Yes . Ive updated my Github account! Cheers!

Advertisements

2 comments

  1. Learn LaTeX. Much easier to enter mathematical equations. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: