Complete Square Root Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The completed program is given below

Complete Square Root Program

In the completed program, the roles of oldGuess and of newGuess can both be played by the variable guess. The value for oldGuess is used on the right of the = sign. After a value for newGuess is calculated, it is assigned to the variable guess on the left of the = sign.

class  SquareRoot
{

  public static void main( String[] args ) 
  {
    final double smallValue = 1.0E-14 ;
    double N     = 3.00 ;
    double guess = 1.00 ;

    while ( Math.abs( N/(guess*guess) - 1.0 ) > smallValue )
    {
       // calculate a new value for the guess
       guess =  N/(2*guess) + guess/2 ;

    }

    System.out.println("The square root of " + N + " is " + guess ) ;
  }

}

Here is the output of the program:

C:JavaLessons/chap19>java SquareRoot

The square root of 3.0 is 1.7320508075688772

The last several digits of this output are probably in error since the program only computes 14 decimal places of accuracy.

QUESTION 17:

If you asked for more accuracy than is possible in double precision variables, what might happen? For example, say that smallValue were 1.0E-21?