Answer:

Yes. Things work fine, except at the end. Each time through the outer loop the last statement changes the rate from the value that was just used. When the loop exits (because goal was reached), it is this new rate that is printed, not the rate used in the calculation that reached the goal.

Newton's Method

Enough about boring financial stuff.

The library java.lang.Math contains the square root function as well as many other functions like sine, cosine, and absolute value. (Look back into Chapter 11 for more on this topic.) The functions in this library have been carefully written and tested by programmers who are experts in numerical analysis. Ordinarily, you would use a method from this library to compute a square root. Here, let us investigate how the square root function could be written.

Newton's method of computing a square root of a number N is to make a first guess, then to improve that guess to get a better guess, then to impove the better guess to get an even better guess, and so on. The guess improvement process is given by a formula:

newGuess = N/(2*oldGuess) + oldGuess/2

The reason this works is in your calculus book, but all you need to do in this program is know how to use the formula.

For example, say that you want the square root of N = 3.00. The first guess can be nearly any value. 1.0 is good enough.

oldGuess N/(2*oldGuess)oldGuess/2newGuess
1.0 1.5 0.5 2.0
2.0 0.75 1.0 1.75
1.75 0.85714 0.875 1.73214
1.73214 0.86598 0.86607 1.73205

The fourth new guess is pretty close:

1.73205*1.73205 = 2.99999

You can't always count on getting good results in four steps, however. A program should keep improving the guess and stop when the results are nearly correct, however long that takes.

QUESTION 14:

Why not keep looping until the results are exactly correct?