Saturday, 1 December 2012

Bisection Method




       §       /*Bisection Method*/
#include<stdio.h>
#include<math.h>
//#include<conio.h>

#define f(x) (x*x*x-4*x*x-9*x-12)

void main()
{
       void bisect(float *x,float a,float b,int*itr);
       int N,itr=0;
       float a,b,err,x,x1;

       printf("\n -----BISECTION METHOD FOR SOLVING NONLINEAR EQUATIONS-----\n\n
       equation is to be given after define\n\n\n");
       printf("enter the starting values,max error, maximum iteration\n");
       scanf("%f%f%f%d",&a,&b,&err,&N);
       bisect(&x,a,b,&itr);
       if(f(a)*f(b)>0)
       {
printf("\nThe initial values do not enclose any roots,choose different        values\n");
              getch();
              exit(2);
       }


       while(itr<N)
       {
              if(f(a)*f(x)<0)
                     b=x;
              else
                     a=x;
              printf("x1=%f & x2=%f\n",a,b);
              bisect(&x1,a,b,&itr);
             
              if(fabs(x1-x)<err)
              {
              printf("after %dth iterations,root=%6.9f\n",itr,x1);
              getch();
              exit(1);
        }
              else
                     x=x1;
       }
       printf("\nerror and iteration conditions do no match\n");
       getch();
}


              //function bisection//
              void bisect(float *x,float a,float b,int*itr)
              {
                     *x=(a+b)/2;
                     ++(*itr);
                     printf("\niteration no %4d gives\t x=%7.5f\n",*itr,*x);
              }

ª      Results: (Bisection Method)
 -----BISECTION METHOD FOR SOLVING NONLINEAR EQUATIONS-----
 equation is to be given after define
enter the starting values,max error,maximum iteration
2 9 .005 99
iteration no    1 gives  x=5.50000
x1=5.500000 & x2=9.000000
iteration no    2 gives  x=7.25000
x1=5.500000 & x2=7.250000
iteration no    3 gives  x=6.37500
x1=5.500000 & x2=6.375000
iteration no    4 gives  x=5.93750
x1=5.500000 & x2=5.937500
iteration no    5 gives  x=5.71875
x1=5.718750 & x2=5.937500
iteration no    6 gives  x=5.82813
x1=5.828125 & x2=5.937500
iteration no    7 gives  x=5.88281
x1=5.828125 & x2=5.882813
iteration no    8 gives  x=5.85547
x1=5.855469 & x2=5.882813
iteration no    9 gives  x=5.86914
x1=5.869141 & x2=5.882813
iteration no   10 gives  x=5.87598
x1=5.875977 & x2=5.882813
iteration no   11 gives  x=5.87939
after 11th iterations,root=5.879394531

ª      Results: (Bisection Method alternative)
 -----BISECTION METHOD FOR SOLVING NONLINEAR EQUATIONS-----
 equation is to be given after define
enter the starting values,max error, maximum iteration
2 3 .005 98
The initial values do not enclose any roots, choose different values

No comments:

Post a Comment