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

#include <stdio.h>

int
main (void)
{
  /* 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), and f(m) */
  double accuracy = 0.0001;  /* desired accuracy of result */
  int numAssigned; /* return value for user input from scanf */

  /* Getting started */
  printf ("Program to compute a square root\n");
  printf ("Enter positive number: ");
  numAssigned = scanf ("%lf", &t);

  /* Validate user input */
  if (numAssigned == 0) {
    printf ("Error: Unable to read number\n");
    return 1;
  } else if ( t <= 0) {
    printf("Error: A positive number is required; %lf was entered.\n", t);
    return 1;
  }
   
  /* Set up initial interval for the bisection method */
  a = 0;
  b = (t < 2.0 ? 2.0 : t );
   
  fa = a*a - t;
  fb = b*b - t;

  /* Iterate interval shrinking until sufficiently small */
  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;
} // main
