go to previous page   go to home page   go to next page hear noise highlighting

Answer:

Yes, there is a bug. Things work fine, except at the end.

The outer loop's last statement changes the rate from the value that was just used. When the loop exits (when goal is reached), it is this new rate that is printed, not the rate used in the calculation that reached the goal.

The boundaries of loops (the start and the end) are especially prone to errors.

The final println could be changed to print (rate-0.001) to fix this. (But this is awkward.)

Or you could use a second variable nextRate which is incremented at the bottom of the loop and is assigned to rate at the top of the loop. (Even more awkward.)

The best version is the original program.


Newton's Method

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

Enough about boring financial stuff. Who wants to be a millionaire, anyway?

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 13 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 improve 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 for this program is to use the formula.

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

The new guess is then

newGuess = 3/(2*1) + 1/2 = 3/2 + 1/2 = 2.0

Now this guess is improved by using it as the oldGuess in the formula.

newGuess = 3/(2*2.0) + 2.0/2 = 3/4 + 1.0 = 1.75

The fifth 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.


QUESTION 14:

Why not keep looping until the results are exactly correct?


go to previous page   go to home page   go to next page