Newton’s Method

Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.

better =  1/2 * (approx + n/approx)

The following implementation of Newton’s method requires two parameters.




(chp07_newtonsdef)

This implementation, shown in codelens, uses a while condition to execute until the approximation is no longer changing. Each time through the loop we compute a “better” approximation using the formula described earlier. As long as the “better” is different, we try again. Step through the program and watch the approximations get closer and closer.

(chp07_newtonswhile)

Note

The while statement shown above uses comparison of two floating point numbers in the condition. Since floating point numbers are themselves approximation of real numbers in mathematics, it is often better to compare for a result that is within some small threshold of the value you are looking for.

Next Section - Exercises