This method for calculating the square root of a number N starts by making a (non zero) guess at the square root. It then uses the original guess to calculate a new guess, according to the formula
newGuess = ((N / oldGuess) + oldGuess) / 2.0;Have two variables oldGuess and newGuess. Initialize oldGuess to N/2 and calculate newGuess according to the above formula. Then use a while loop to iterate as long as the absolute value of the difference between the oldGuess and newGuess is greater than 1.0E-06. Reset the value of oldGuess to the value of the newGuess and then recompute the value of newGuess with that value of the oldGuess according to the above formula in the body of the loop.
In your program you will prompt the user to enter a positive number. If the number is negative, print an error message and ask the user to try again. For a positive number, calculate the square root using the above method. Find the difference between the square root you obtained and the value obtained from Math.sqrt(). Write out the value the user entered, the square root you computed, and the difference (your square root - Math.sqrt()).
There is a piece of trivia associated with this algorithm. Professional mathematicians are familiar with this algorithm as Newton's method. But the algorithm is much older than Newton. In first century AD, the Greek mathematician Heron of Alexandria used this method to determine the square root of 720. There is evidence that this method goes even further back, as far as the Babylonians. In the Yale University Babylonian Collection, there is a cuneiform tablet that seems to use this method to calculate the square root of 2.
You can refine the initial guess so that the method converges faster. We know that the square root of 100 is 10, so a better initial guess for the square root of any 3 or 4 digit number is 10. Likewise, we know that the square root of 10,000 is 100, so a better initial guess for the square root of any 5 or 6 digit number is 100. And so on.
We will be looking at good documentation, descriptive variable names, and adherence to the coding convention mentioned below. Your file CalcSqrt.java will have the following header:
/* File: CalcSqrt.java Description: Student Name: Student UT EID: Course Name: CS 303E Unique Number: Date Created: Date Last Modified: */
You will follow the standard Java Coding Conventions. You can either view the HTML page or download the PDF or Postscript and print it out. There is a modification that I would like to make to the standard coding conventions. Please align the opening and closing braces vertically so that you can easily make out the blocks of code. For example:
Do this: if ( x > 5 ) { a = b + c; } Not this: if ( x > 5 ) { a = b + c; }
Use the turnin program to submit your .java file. The TAs should receive your work by 5 PM on Friday, 10 July 2009. There will be substantial penalties if you do not adhere to the guidelines.