By primitive expressions, I mean + - * / sqrt, unless there are others that I am missing. I’m wondering how to write a Scheme expression that finds the 6th root using only these functions.
I know that I can find the cube root of the square root, but cube root doesn’t appear to be a primitive expression.
Consider expt, passing in a fractional power as its second argument.
But let’s say we didn’t know about
expt. Could we still compute it?One way to do it is by applying something like Newton’s method. For example, let’s say we wanted to compute n^(1/4). Of course, we already know we can just take the
sqrttwice to do this, but let’s see how Newton’s method may apply to this problem.Given
n, we’d like to discover rootsxof the function:Concretely, if we wanted to look for
16^(1/4), then we’d look for a root for the function:We already know if we plug in
x=2in there, we’ll discover that2is a root of this function. But say that we didn’t know that. How would we discover thexvalues that make this function zero?Newton’s method says that if we have a guess at
x, call itx_0, we can improve that guess by doing the following process:where
f'(x)is notation for the derivative off(x). For the case above, the derivative off(x)is4x^3.And we can get better guesses
x_2,x_3, … by repeating the computation:until we get tired.
Let’s write this all in code now:
The code above just expresses
f(x),f'(x), and the idea of improving an initial guess five times. Let’s see what the value ofapprox-quad-root-of-16is:Hey, cool. It’s actually doing something, and it’s close to
2. Not bad for starting with such a bad first guess of1.0.Of course, it’s a little silly to hardcode
16in there. Let’s generalize, and turn it into a function that takes an arbitraryninstead, so we can compute the quad root of anything:Does this do something effective? Let’s see:
Cool: it is doing something useful. But note that it’s not that precise yet. To get better precision, we should keep calling
improve, and not just four or five times. Think loops or recursion: repeat the improvement till the solution is “close enough”.This is a sketch of how to solve these kinds of problems. For a little more detail, look at the section on computing square roots in Structure and Interpretation of Computer Programs.