Wednesday, October 5, 2016

Numerical Method-2: Coding for Bisection Method

#include <stdio.h>
#include <math.h>
float fnct(float x)
{
return (x*x - 4*x -10);}
int main()
{
int i=0;
float xl, xu, x0, e = 0.0001;
float fxl,fxu,fx0,error,root;
printf("\nEnter values for xl and xu:\n");
scanf("%f %f", &xl, &xu);
fxl= fnct(xl);  fxu= fnct(xu);
if(fxl*fxu>0)
{ printf("Not in range\n");}
else
{   printf("Iter \t xl \t xu \t x0 \t fxo \t\t error \n\n ");
   while(1)
   {
        i++;
     x0 =(xl + xu)/2; fx0 = fnct(x0);
        if ( fxu* fx0 <= 0)
            xl = x0;
        else
            xu = x0;    error=fabs((xu - xl)/xl) ;
           printf("%d\t%.2f\t%.2f\t%.2f\t%f.2\t%.2f\n ",i,xl,xu,x0,fx0,error);
           if (fabs((xu - xl)/xl) < e)
         {  root = (xu+xl)/2;
            printf("Root= %6.4f\n", root);
            break;
         }
    }

}
return  0;
}


Output for Bisection Method



No comments:

Post a Comment