CS 1073 Introductory Programming
for Scientific Applications
Bisection Method
for Finding Roots


Finding roots of an equation using the bisection method: The programs below illustrate this.

Bisection Method

public class Bisection {

   // f: a function to solve for
   public double f(double x) {
      return 2 - x*x;
   }

   // findRoot: the root of a function
   public double findRoot(double lo, double hi) {
      double mid, fLo, fHi, fMid;
      do {
         mid = (lo + hi)/2;
         System.out.println("lo: " + lo + 
            ",\t hi: " + hi);
         fLo = f(lo); fHi = f(hi); fMid = f(mid);
         System.out.println("    mid: " + mid + 
            ",\tfMid: " + fMid);
         if (fMid < 0) hi = mid;
         else lo = mid;
      } while (hi - lo > 1.0E-15);
      return mid; 
   }

   public static void main(String[] args) {
      Bisection b = new Bisection();
      double root = b.findRoot(0, 2);
      System.out.println("Root:    " + root);
      System.out.println("Sqrt(2): " + Math.sqrt(2));
   }
 }

Here are results of a run.