C code using Runge-Kutta 4th order method

Problem: Here we have to find y(0,2) and y(0,4), Given dy/dx=1+y^2 where y=0 when x=0

Algorithm:

Step 1: input x0,y0,h,last point n

Step 2:m1=f(xi,yi)

Step 3:m2=f(xi+h/2,yi+m1h/2)

Step 4:m3=f(xi+h/2,yi+m2h/2)

Step 5:m4=f(xi+h,yi+m3h)

Step 6:yi+1=yi+(m1+2m2+2m3+m4/6)h

Step 5:Display output

Code:

#include<stdio.h>
#include <math.h>
#include<conio.h>
#define F(x,y)  1 + (y)*(y)
void main()
{
    double y0,x0,y1,n,h,f,k1,k2,k3,k4;
    system("cls");
    printf("\nEnter the value of x0: ");
    scanf("%lf",&x0);
    printf("\nEnter the value of y0: ");
    scanf("%lf",&y0);
    printf("\nEnter the value of h: ");
    scanf("%lf",&h);
    printf("\nEnter the value of last point: ");
    scanf("%lf",&n);
    for(; x0<n; x0=x0+h)
    {
        f=F(x0,y0);
        k1 = h * f;
        f = F(x0+h/2,y0+k1/2);
        k2 = h * f;
        f = F(x0+h/2,y0+k2/2);
        k3 = h * f;
        f = F(x0+h/2,y0+k2/2);
        k4 = h * f;
        y1 = y0 + ( k1 + 2*k2 + 2*k3 + k4)/6;
        printf("\n\n  k1 = %.4lf  ",k1);
        printf("\n\n  k2 = %.4lf ",k2);
        printf("\n\n  k3 = %.4lf ",k3);
        printf("\n\n  k4 = %.4lf ",k4);
        printf("\n\n  y(%.4lf) = %.3lf ",x0+h,y1);
        y0=y1;
    }
    getch();
}

 Output:

runge kutta

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.