Bisection Method

This method is also called "Mid-Point Method".
ALGORITHM:
  1. START.
  2. Input initial values x1 and x2.
  3. Compute f1=f(x1) and f2=f(x2).
  4. If f1*f2>0, x1 and x2 do not bracket the the root and go to step 2.
  5. Compute xm=(x1+x2)/2 and fm=f(xm).
  6. If f1*fm<0, set x2=xm and set f2=fm, Else x1=xm and f1=fm.
  7. If |(x2-x1)/xm|<accuracy, then root = xm, Else go to step 5.
  8. STOP
PROGRAM in C:
#include<stdio.h>
#include<math.h>
#include<conio.h>

float f(float x)
{
  return(x*x*x+x*x-3*x-3);
}

void main()
{
  float x1,x2,xm=0,tmp,eps=0.0001;
  int iteration=0;
  do
  {
    printf("Enter Initial guess");
    scanf("%f %f", &x1,&x2);
    if(f(x1)*f(x2)>0)
      printf("\nInvalid Guess.... Type the guess again...\n");
  }while(f(x1)*f(x2)>0);

  do
  {
    tmp=xm;
    xm=(x1+x2)/2.00;
    iteration++;
    if(f(x1)*f(xm)<0)
        x2=xm;
    else
        x1=xm;
  }while(fabs(xm-tmp)>eps);
  printf("\n Result = %.5f   Iteration=%d",xm,iteration);
  getch();

No comments:

Post a Comment