Sunday, 2 August 2015

C Code For Bisection Method

Bisection Method: The following method is used to find the accurate roots of transcendental equation and polynomial equation.
The transcendental equation is the equation which contains trigonometric,algorithmic and exponential functions associated with it for ex: xsinx-logx+1=0. With the help of following code every time you can modify your function and can find root in one go without any pen and paper. Lets get started...

PSEUDO CODE: 

1)First we will input two intervals for desirable function.
2)We will check whether their function values lies in range or not if yes then programme continue else it will display wrong intervals and will exit the programme.
3)If intervals will be correct then value of x2 will be find out and for every interval its function value    will be stored.
4)Again we will check function values of intervals and accordingly intervals will be assigned
5)This whole programme will be exectued untill we will find our root upto desirable decimal place 

C-Code:

#include<stdio.h>
#include <math.h>
#include<conio.h>
#define ESP 0.001 //For finding root upto desirable decimal digit
#define F(x) (x)*(x)*(x) + (x)*(x) + (x) + 7 //For defining function
void main()
{
  int i = 1;
  float x0,x1,x2; //Intervals
  double f1,f2,f0,t; //Function

  printf("\nEnter the value of x0: ");
  scanf("%f",&x0);

  printf("\nEnter the value of x1: ");
  scanf("%f",&x1);
  if(f0*f1<0)
 { printf("\n__________________________________________________________________\n");
  printf("\niteration\t x0\t       x1\t x2\t   f0\t   f1\t   f2");
  printf("\n___________________________________________________________________\n");
  do
  {
  x2=(x0+x1)/2;
  f0=F(x0);
  f1=F(x1);
  f2=F(x2);
  printf("\n%d %f %f %f %lf %lf %lf", i, x0,x1,x2,f0,f1,f2);
  if(f0*f2<0)
   {
    x1=x2;
   }
   else
   {
    x0=x2;
   }
   i++;
  }while(fabs(f2)>ESP);
printf("\n__________________________________________________________\n");
printf("\n\nApp.root = %f",x2);
}
else 
{ printf("\nIntervals are not correct\n");
   exit(0);
}
getch();
}
NOTE:
this code is written in codeblocks GNU GCC compiler
this code might encounter issues when tried to run in turboC or any other compiler

No comments:

Post a Comment