Wednesday, 17 December 2014

Pin It

Widgets

Find root using Bisection Method


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

#define F(x) ((2*x)+1)
#define ERROR 0.00001

float Bisection(float a, float b)
{ 
 float mid;
 do
 {
  mid = (a+b)/2;
  printf("F(a): %f, F(b) : %f, F(mid) : %f\n", F(a), F(b), F(mid));

  if((F(mid)>0 && F(a)>0) || (F(mid)<0 && F(a)<0))
  {
   a = mid;
  }
  else
  {
   b = mid;
  }
  
  
 } while(fabsf(F(mid)) > ERROR);
 
 return a;
}

int main()
{
 float a = -2.5;
 float b = 2.5;
 
 printf("Finding root in the interval [%f, %f]\n", a, b);
 
 if((F(a)>0 && F(b)>0) || (F(a)<0 && F(b)<0))
 {
  printf("No root lie in the interval [%f, %f]", a, b);
 }
 else
 {
  printf("The root is : %f\n", Bisection(a, b));
 }
 
 return 0;
}

No comments: