/*
 * Bisect.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Numerical Computation'
 * section: `Finding a Root by Bisection'
 *
 * This program finds a zero of a function f within a given interval.
 * It assumes that the function has different signs at the two ends.
 * It acts by repeatedly bisecting the interval and closing in on the
 * half which contains the root.
 */
public class Bisect
{
  // The function that we are going to
  // find a root for.
  public static double f(double x)
  {
    return 2 + x*x - (x-1)*x*x;
  }


  // The `main' method at which program
  // execution starts.
  public static void main(String[] argv)
  {
    double left, right, middle, middley;

    // Start considering the interval from
    // 0 to 3. We assume that function is
    // changes sign over this interval.
    left = 0;
    right = 3;
    if (f(left) * f(right) > 0)
      System.out.println("Function does not change sign");
    else
    {
      // Keep halving the size of the interval
      // until it is as small as our required
      // accuracy.
      while (right - left > 0.0001)
      {
        // Compute the value of the function
        // At the middle of the interval
        middle = (left + right) / 2;
        middley = f(middle);

        // Switch to using whichever half
        // the sign now changes in.
        if (middley * f(right) <= 0)
        {
          left = middle;
        }
        else
        {
          right = middle;
        }
      }

      // Output our result.
      System.out.println("Root is at");
      System.out.println(left);
    }
  }
}

