import java.util.Scanner;
/*******************************************************************************/
/**
 * This is simple implementation of Newton's method for finding the square
 * root of a number.  We iterate
 *
 *       newApprox = (oldApprox + x/oldApprox)/2.0
 *
 * until the difference between the next and the previous approximation to the
 * root is smaller than some predetermine tolerance 'epsilon'.  For square roots
 * we can start with the value of the approximate root equal to the original
 * number.
 *
 * For testing purposes, we can compare the approximate root we get from this
 * method with the root returned by the 'Math.sqrt()' method.  In theory, we
 * could make our approximation as good as we wanted by simply choosing the
 * value of 'epsilon' as small as possible.
 *
 * @author Duncan Buell
 * 4 February 2008
**/

public class MySquareRootMain
{
  public static void main (String[] args)
  {
    double epsilon,newApprox,oldApprox,x;
    Scanner console = new Scanner(System.in);

    System.out.println("Enter the tolerance epsilon for successive approximations: ");
    epsilon = console.nextDouble();

    System.out.println("Enter the number for which to take the square root: ");
    x = console.nextDouble();

    System.out.println("Compute the square root of " + x);
    System.out.println("Stop when the difference between successive approximations is < " + epsilon);
    oldApprox = Double.POSITIVE_INFINITY;
    newApprox = x;

    while(epsilon < (Math.abs(oldApprox-newApprox)))
    {
      oldApprox = newApprox;
      newApprox = (oldApprox + x/oldApprox)/2.0;
      System.out.println("new approximation is " + newApprox);
    }

    System.out.println("Approximate square root of " + x + " is " + newApprox);
    System.out.println("Built in function says root of " + x + " is " + Math.sqrt(x));
    System.out.println("The discrepancy is " + Math.abs(Math.sqrt(x) - newApprox));

  }
} // public class MySquareRootMain

