Étude 4-5: Recursion with a Helper Function

In this exercise, you will add a function nth_root/2 to the powers module. This new function finds the nth root of a number, where n is an integer. For example, nth_root(36, 2) will calculate the square root of 36, and nth_root(1.728, 3) will return the cube root of 1.728.

The algorithm used here is the Newton-Raphson method for calculating roots. (See http://en.wikipedia.org/wiki/Newton%27s_method for details).

You will need a helper function nth_root/3, whose parameters are X, N, and an approximation to the result, which we will call A. nth_root/3 works as follows:

  • Calculate F as (AN - X)
  • Calculate Fprime as N * A(N - 1)
  • Calculate your next approximation (call it Next) as A - F / Fprime
  • Calculate the change in value (call it Change) as the absolute value of Next - A
  • If the Change is less than some limit (say, 1.0e-8), stop the recursion and return Next; that’s as close to the root as you are going to get.
  • Otherwise, call the nth_root/3 function again with X, N, and Next as its arguments.

For your first approximation, use X / 2.0. Thus, your nth_root/2 function will simply be this:

nth_root(X, N) → nth_root(X, N, X / 2.0)

Use io:format to show each new approximation as you calculate it. Here is some sample output.

1> c(roots).
{ok,roots}
2> roots:nth_root(27, 3).
Current guess is 13.5
Current guess is 9.049382716049383
Current guess is 6.142823558176272
Current guess is 4.333725614685509
Current guess is 3.3683535855517652
Current guess is 3.038813723595138
Current guess is 3.0004936436555805
Current guess is 3.000000081210202
Current guess is 3.000000000000002
3.0

See a suggested solution in Appendix A.

Get Études for Erlang now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.