CS 1073 Introductory Programming
for Scientific Applications
Newton's Method
for Finding Roots


Finding roots of an equation using Newton's method: The programs below illustrate this.

Newton's Method: Square root of 2

public class SquareRoot {

   // findRoot: the root of a function
   public double findRoot() {
      double xOld = 2; 
      double xNew;
      do {
         xNew = xOld/2 + 1/xOld;
         System.out.println("xNew: " + xNew);
         if (Math.abs(xNew - xOld) < 1.0E-15) break;
         xOld = xNew;
      } while (true);
      return xNew; 
   }

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

Here are results of a run.


Newton's Method: Square root of n

public class SquareRootN {

   // findRoot: the root of a function
   public double findRoot(double n) {
      double xOld = 2; 
      double xNew;
      do {
         xNew = xOld/2 + n/(2*xOld);
         System.out.println("xNew: " + xNew);
         if (Math.abs(xNew - xOld) < 1.0E-15) break;
         xOld = xNew;
      } while (true);
      return xNew; 
   }

   public static void main(String[] args) {
      double n = 3;
      SquareRootN sq = new SquareRootN();
      double root = sq.findRoot(n);
      System.out.println("Root:    " + root);
      System.out.println("Sqrt(" + n + "): " + Math.sqrt(n));
   }
 }

Here are results of a run.

Now stick in 100 in place of 3 above.

Now stick in 10000 in place of 3 above.