Calculatinf solution of an equation using Bisection Method

Problem statement
Write a program that uses the bisection algorithm to find  a root of 
the equation x2 − 2 = 0. 
The method of successive bisection works as follows: Start with a lower bound l and an 
upper bound u such that  f(l)*f(u) > 0, ie, f(l) and f(u) are of opposite signs. Then there is 
a foot of f(x) between l and u. Write a loop where in each iteration, you compute the 
middlepoint (mid) of the current interval [l, u]. Evaluate f(mid), and based on the sign of 
f(mid), change the current interval to [l, mid] or to [mid, u]. The loop terminates when 
width of the interval becomes smaller than  10−6


#include<stdio.h>
float evaluate_quad(float start,float end);
float value(float x);
int main()
{
  float start,end,y;
  printf("enter starting point ");
  scanf("%f",&start);
  printf("enter ending point ");
  scanf("%f",&end);
  y=evaluate_quad(start,end);
  printf("the answer is %f\n",y);
  return 0;
}
float evaluate_quad(float start,float end)
{
  float left,rigth,middle,tempst,tempen,tempmi;
  tempst=value(start);
  tempen=value(end);
  if(tempen<0 &&tempst<0)
    {
      printf("no solution found in this given range !!\n");
      return 0;
    }
  else if(tempen>0 && tempst>0)
    {
      printf("no solution found in this given range !!\n");
      return 0;
    }
  do
    {
      middle=(start+end)/2.0;
      tempst=value(start);
      tempmi=value(middle);
      if(tempst<0&&tempmi>0)
    {
      end=middle;
    }
      else if(tempst<0&&tempmi<0)
    {
      start=middle;
    }
      else if(tempst>0&&tempmi<0)
    {
      end=middle;
    }
      else
    {
      start=middle;
    }
      break;
    }while(end-start>.1);         /* this is presision of the program this an also be varied */ 
  return start;
}
float value(float x)
{
  float result;
  result=(x*x)-2.0;     /* you can make the function accordingly which function you want */
  return result;
}

2 comments: