A number of ordinary differential equations come in engineering and all of them may not be solved by analytical method. In order to solve or get numerical solution of such ordinary differential equations, Runge Kutta method is one of the widely used methods.
Unlike like Taylor’s series, in which much labor is involved in finding the higher order derivatives, in RK4 method, calculation of such higher order derivatives is not required. (Derivation)
This C program for Runge Kutta 4 method is designed to find out the numerical solution of a first order differential equation. It is a kind of initial value problem in which initial conditions are known, i.e the values of x0 and y0 are known, and the values of y at different values x is to be found out.
The source code below to solve ordinary differential equations of first order by RK4 method first asks for the values of initial condition i.e. user needs to input x0 and y0 . Then, the user has to define increment ‘h’ and the final value of x at which y is to be determined.
In this program for Runge Kutta method in C, a function f(x,y) is defined to calculate slope whenever it is called.
f(x,y) = (x-y)/(x+y)
Source Code for Runge Kutta Method in C:
#include<stdio.h>
#include<math.h>
float f(float x,float y);
int main()
{
float x0,y0,m1,m2,m3,m4,m,y,x,h,xn;
printf("Enter x0,y0,xn,h:");
scanf("%f %f %f %f",&x0,&y0,&xn,&h);
x=x0;
y=y0;
printf("\n\nX\t\tY\n");
while(x<xn)
{
m1=f(x0,y0);
m2=f((x0+h/2.0),(y0+m1*h/2.0));
m3=f((x0+h/2.0),(y0+m2*h/2.0));
m4=f((x0+h),(y0+m3*h));
m=((m1+2*m2+2*m3+m4)/6);
y=y+m*h;
x=x+h;
printf("%f\t%f\n",x,y);
}
}
float f(float x,float y)
{
float m;
m=(x-y)/(x+y);
return m;
}
Input/Output:
Also see,
Runge-Kutta Method in MATLAB
Numerical Methods Tutorial Compilation
The above C program for Runge Kutta 4 method and the RK4 method itself gives higher accuracy than the inconvenient Taylor’s series; the accuracy obtained agrees up to the term h^r, where r varies for different methods, and is defined as the order of that method.
The RK formulas require the values of function at some selected points only. Further, Euler’s method is the Runge Kutta method of first order.