Recursion: sqrt(x) revisited |
Numerous algorithms exist for determining the square root of a non-negative real number. An interesting one that can be derived from Newton's Method, involves starting with an initial guess followed by successive improvements.
For example, suppose the square root of a number, n, is sought. An initial guess, g0, might be taken as n/g. If g2 is not sufficiently close enough to n, (say, |n-g|< 0.001), we could use the average of g0 and n/g, call it g1, and try again. As a result, our feedback strategy should reveal a sequences of closer approximations to the square root of n.
Program: Write a recursive function,
double sqrt(double n, double g)
that will return an approximation to the square root of n accurate to 0.001. Write a main program to test your function for a variety of well-chosen values for n.