/* Bisection Method for Finding the Square Root of a Positive Number */

#include <stdio.h>

int
main ()
{
  /* pre-conditions:  t will be a positive number
   * post-conditions:  code will print an approximation of the square root of t
   */
 
  double t;        /* we approximate the square root of this number */
  double a, b, m;  /* desired root will be in interval [a,b] with midpoint m */
  double fa, fb, fm;  /* for f(x) = x^2 - t, the values f(a), f(b), f(m), resp. */
  double accuracy = 0.0001;  /* desired accuracy of result */
     
  /* Getting started */
  printf ("Program to compute a square root\n");
  printf ("Enter positive number: ");
  scanf ("%lf", &t);
   
  /* set up initial interval for the bisection method */
  a = 0;
  if (t < 2.0)
    b = 2.0;
  else
    b = t;
   
  fa = a*a - t;
  fb = b*b - t;
   
  while (b - a > accuracy)
    {
      m = (a + b) / 2.0;  /* m is the midpoint of [a,b] */
      fm = m*m - t;
      if (fm == 0.0) break;  /* stop loop if we have the exact root */
      
      if ((fa * fm) < 0.0)
        { /* f(a) and f(m) have opposite signs */
          b = m;
          fb = fm;
        }
      else
        {
          a = m;
          fa = fm;
        }
    } // while
  
  printf ("The square root of %lf is approximately %lf\n", t, m);
  return 0;
}
