Wednesday 9 April 2014

Runge-Kutta 4th order method

#include<stdio.h>
#include<conio.h>
#include<math.h>

float f(float x,float y)
{
    return((1+0.3*x*x*x+0.4*y*y*y)/(1+0.3*x*x+0.4*y*y));
}

void main()
{
    float x0,y0,h,x,y1,k1,k2,k3,k4;
    clrscr();
    printf("\nEnter the initial value of x:");
    scanf("%f",&x0);
    printf("\nEnter the initial value of y:");
    scanf("%f",&y0);
    printf("\nEnter the value to be determined:");
    scanf("%f",&x);
    printf("\nEnter the step length:");
    scanf("%f",&h);
    while(x0<x)
    {
      k1=h*f(x0,y0);
      k2=h*f(x0+h/2,y0+k1/2);
      k3=h*f(x0+h/2,y0+k2/2);
      k4=h*f(x0+h,y0+k3);
      x0+=h;
      y1=y0+(k1+2*k2+2*k3+k4)/6;
      printf("\n\t\t y(%0.1f)=%0.5f",x0,y1);
     y0=y1;
   }
    printf("\n\n\n  Hence the required value of y(%0.1f)=%0.5f(correct to 5D)",x0,y1);
   getch();
}

Tuesday 1 April 2014

Gauss–Seidel method

#include<stdio.h>
#include<conio.h>
#include<math.h>
#define ESP 0.0001
#define X1(x2,x3) ((17 - 20*(x2) + 2*(x3))/20)
#define X2(x1,x3) ((-18 - 3*(x1) + (x3))/20)
#define X3(x1,x2) ((25 - 2*(x1) + 3*(x2))/20)


void main()
{
  double x1=0,x2=0,x3=0,y1,y2,y3;
  int i=0;
  clrscr();
  printf("\n__________________________________________\n");
  printf("\n   x1\t\t   x2\t\t   x3\n");
  printf("\n__________________________________________\n");
  printf("\n%f\t%f\t%f",x1,x2,x3);
  do
  {
   y1=X1(x2,x3);
   y2=X2(y1,x3);
   y3=X3(y1,y2);
   if(fabs(y1-x1)<ESP && fabs(y2-x2)<ESP && fabs(y3-x3)<ESP )
   {
     printf("\n__________________________________________\n");
     printf("\n\nx1 = %.3lf",y1);
     printf("\n\nx2 = %.3lf",y2);
     printf("\n\nx3 = %.3lf",y3);
     i = 1;
   }
   else
   {
     x1 = y1;
     x2 = y2;
     x3 = y3;
     printf("\n%f\t%f\t%f",x1,x2,x3);
   }
  }while(i != 1);
getch();
}

Gauss Elimination Method

#include<stdio.h>
#include<math.h>
int main()
{
int n=3,i,j,k;
float a[10][10],c[10],x[10];
printf("Enter the no. of equations :\n");
scanf("%d", &n);
printf("Enter the right hand side of equation ");
for(i=0;i<=n-1;i++)
{
scanf("%f",&c[i]);
}

for(i=0;i<=n-1;i++)
{
printf("Enter the coefficient of equation %d.\n",i+1);
for(j=0;j<=n-1;j++)
{
scanf("%f",&a[i][j]);
}

}

for(k=0;k<=n-2;k++)
{
for(i=k+1;i<=n-1;i++)
{
for(j=k+1;j<=n-1;j++)
{
a[i][j]=a[i][j]-((a[i][k]/a[k][k])*a[k][j]);
}
c[i]=c[i]-((a[i][k]/a[k][k])*c[k]);
}

}

for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
printf("%f ",a[i][j]);
}
printf("\n");
}
printf("\n");

x[n-1]=c[n-1]/a[n-1][n-1];
printf("The solution is :\n");
printf("x[%d] = %f\n",n-1,x[n-1]);
for(k=0;k<=n-2;k++)
{
i=n-k-2;
for(j=i+1;j<=n-1;j++)
{
c[i]=c[i]-(a[i][j]*x[j]);
}
x[i]=c[i]/a[i][i];
printf("x[%d] = %f\n",i,x[i]);
}
return 0;
}