3/10/2009

C Program To Find The Root Of The Equation x*x*x-18=0 Using Regula Falsi Method


/* C Program To Find The Root Of The Equation x*x*x-18=0 Using Regula Falsi Method */


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

float f(float);
int main()
{
    float x0,x1,x2,y0,y1,y2,e;
    int i,n;

      printf("Enter the initial guess\n");
          scanf("%f%f",&x0,&x1);
       y0=f(x0);
       y1=f(x1);

       if((y0*y1)>=0)
       {
           printf("Invalid guess.\n");
           exit(0);
       }
      printf("Enter the allowable error:\n");
          scanf("%f",&e);
      printf("Enter the number of iterations:\n");
          scanf("%d",&n);

      printf("f(x)=x*x*x-18\n");
      printf("-------------------------------------------------------\n");
      printf("i\tx0\tx1\ty0\ty1\tx2\ty2\n");
      printf("-------------------------------------------------------\n");
      for(i=0;i<n;i++)
      {
          x2=((x0*y1)-(x1*y0))/(y1-y0);
          y2=f(x2);

          printf("%d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",i,x0,x1,y0,y1,x2,y2);

          if(fabs(y2)<=e)
          {
              printf("-------------------------------------------------------\n");
              printf("Converges to a root at %d iteration.\n",i);
              printf("Root is %.3f",x2);
              exit(0);
          }
          if(y0*y2>0)
          {
              x0=x2;
              y0=y2;
          }
          else{
            x1=x2;
            y1=y2;
          }
      }
      printf("-------------------------------------------------------\n");
      printf("Does not converges to root in %d iterations.\n",i);
      printf("Root is= %.3f\n",x2);

        return 0;
}
   float f(float x)
   {
       return(x*x*x-18);
   }
Out Put:
Enter the initial guess
2
3
Enter the allowable error:
0.001
Enter the number of iterations:
6
f(x)=x*x*x-18
-------------------------------------------------------
i       x0      x1      y0      y1      x2      y2
-------------------------------------------------------
0       2.000   3.000   -10.000 9.000   2.526   -1.876
1       2.526   3.000   -1.876  9.000   2.608   -0.261
2       2.608   3.000   -0.261  9.000   2.619   -0.035
3       2.619   3.000   -0.035  9.000   2.621   -0.005
4       2.621   3.000   -0.005  9.000   2.621   -0.001
-------------------------------------------------------
Converges to a root at 4 iteration.
Root is 2.621

No comments:

Post a Comment