Monday, June 27, 2016

RUNGE – KUTTA METHOD


            Runge – kutta(RK)  is also the one of the methods to solve the ordinary differential equation. This method does not require the calculation of higher order derivatives and gives greater efficiency. The RK formulae posses the advantages of requiring only the functional values at some selected points. These methods agree with Taylor’s series solution up to the hr  term where ‘r’ differ from method to method and is called order of that methods. 



Source Code for RK Method


#include<iostream>
#include<cmath>
using namespace std;

float func(float x, float y){
    return -2*x-y;
}

int main(){
    float k[4]={0}, h=0.05, x=0.0, X=0.64, y=-1.0;  //f(0.6) = -0.846435
//    float k[4]={0}, h, x, y, X;
//    cout<<"Enter initial values of x (X0) and y (Y0) , final value of x (Xn) and the step value (h) :\n";
//    cin>>x>>y>>X>>h;
    do{
        y = y + (k[0]+2*k[1]+2*k[2]+k[3])/6;
        cout<<"f("<<x<<") =\t"<<y<<endl;
        k[0] = h*func(x,y);
        k[1] = h*func(x+h/2, y+k[0]/2);
        k[2] = h*func(x+h/2, y+k[1]/2);
        k[3] = h*func(x+h, y+k[2]);
        x = x + h;
    }while(x<=X);
    cout<<endl<<"f("<<X<<") = "<<y<<endl;
    return 0;
}

Source Code for RK-2 Method

#include<iostream>
using namespace std;
float func_f(float x,float y, float z)
{
    return z;
}
float func_g(float x,float y,float z)
{
    return -(x*z+y);
}
int main()
{
    float x=0.0, X=0.4, h=0.2, y=1, m[4], l[4], z=0.0;
    do
    {
        cout<<"("<<x<<", "<<y<<", "<<z<<")"<<endl;
        m[0]=func_f(x,y,z);
        l[0]=func_g(x,y,z);
        m[1]=func_f(x+h/2,y+(m[0]*h)/2,z+(l[0]*h)/2);
        l[1]=func_g(x+h/2,y+(m[0]*h)/2,z+(l[0]*h)/2);
        m[2]=func_f(x+h/2,y+(m[1]*h)/2,z+(l[1]*h)/2);
        l[2]=func_g(x+h/2,y+(m[1]*h)/2,z+(l[1]*h)/2);
        m[3]=func_f(x+h,y+(m[2]*h),z+(l[2]*h));
        l[3]=func_g(x+h,y+(m[2]*h)/2,z+(l[2]*h));
        y+=h*((m[0]+2*m[1]+2*m[2]+m[3])/6);
        z+=h*((l[0]+2*l[1]+2*l[2]+l[3])/6);
        x+=h;
    }while(x<=X);
    return 0;
}

Source Code for RK-4 Method


#include<iostream>
using namespace std;
float slope(float a,float b)
{
    return ((b-a)/(b+a));
}
int main()
{
    float x=0.0,x_n=1.0,h=0.2,y=1.0,k[4]={0.0};
    do
    {
        cout<<"("<<x<<","<<y<<")"<<endl;
        k[0]=h*slope(x,y);
        k[1]=h*slope(x+h/2,y+k[0]/2);
        k[2]=h*slope(x+h/2,y+k[1]/2);
        k[3]=h*slope(x+h/2,y+k[2]/2);
        y+=(k[0]+2*k[1]+2*k[2]+k[3])/6;
        x+=h;
    }while(x<=x_n);
    return 0;
}

No comments:

Post a Comment