Wednesday, May 29, 2013

Solution of Ordinary Differential Equation using Runge-Kutta Method | RK4 method for ODE Solution in C

In numerical analysis, the Runge–Kutta methods are an important family of implicit and explicit iterative methods for the approximation of solutions of ordinary differential equations. These techniques were developed around 1900 by the German mathematicians C. Runge and M. W. Kutta.

There are many variants of the Runge-Kutta method, but the most widely used one is the following known as RK-4 method: 
Given 
y' = f(x,y) 
y(xn) = yn 
we compute in turn 
k1 = hf(xn,yn) 
k 2 = hf (xn+h/2,yn+k1/2)
k3 = hf (xn+h/2,yn+k2/2)
k4 = hf(xn + h, yn + k3) 
yn+1 = yn + (k1 + 2*k2 + 2*k3 + k4 )/6

This algorithm can be implemented  using the following source code in C:


//RK4 Method to solve ODI, @author:Jivan Nepali, Kathmandu
 #include<stdio.h>  
 #include<math.h>  
 float f(float x ,float y)  
 {  
   return (y*y-x*x)/((y*y+x*x));  
 }  
 int main()  
 {  
   float x0,y0,x1,y1,h,k1,k2,k3,k4,k,xn ,x,y;  
   printf("Enter the values of x0 , y0 ,h ,xn :\n");  
   scanf("%f %f %f %f" ,&x0,&y0,&h,&xn);  
   x=x0;  
   y=y0;  
   while(1)  
   {  
     if(x==xn)  
       break;  
     k1=h*f(x,y);  
     k2=h*f(x+h/2,y+k1/2);  
     k3=h*f(x+h/2,k2/2+y);  
     k4=h*f(x+h,y+k3);  
     k=(k1+(k2+k3)*2+k4)/6;  
     x+=h;  
     y+=k;  
     printf("value of x =%7.5f Value of y =%7.5f\n",x,y);  
   }  
   return 0;  
 }  

Enjoy Coding!!!!

No comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...