public class Newton {

/*******************************************************************************/
/**
 * This is simple implementation of Newton's method for finding the root
 * of a function.  We iterate
 *
 *       newApprox = oldApprox - f(oldApprox)/fprime(oldApprox)
 *
 * until the difference between the next and the previous approximation to the
 * root is smaller than some predetermined tolerance 'epsilon'.
 *
 * @author Duncan Buell
 * 24 February 2008
**/

// Note that there is no constructor.  For this particular purpose we can allow
// Java to supply 'the default constructor' since we don't use anything except
// this one method for root finding.  Again, please ignore some of this and
// concentrate on the loop control.  That's the important concept here.

/*******************************************************************************/
/**
 * Java method to find roots by Newton iteration.
**/
  public double findRoot(double x, double epsilon)
  {
    int iterationCount;
    double newApprox,oldApprox;

    oldApprox = Double.POSITIVE_INFINITY;
    newApprox = x;

    iterationCount = 0;
    while( (epsilon < Math.abs(oldApprox-newApprox)) && (10 > iterationCount) )
    {
      ++iterationCount;
      oldApprox = newApprox;
      newApprox = oldApprox - MyFunctions.f(oldApprox)/MyFunctions.fprime(oldApprox);
      System.out.println("oldApprox is " + oldApprox);
      System.out.println("f(oldApprox) is " + MyFunctions.f(oldApprox));
      System.out.println("fprime(oldApprox) is " + MyFunctions.fprime(oldApprox));
      System.out.println("new approximation is " + newApprox);
      System.out.println("");
    }

    return newApprox;
  }
} // public class Newton

