Solutions: If evaluation and square roots by Newton’s Method:
Alyssa P. Hacker decides to make a new version of
if in terms of
cond as a procedure. The
new-if seems to work for basic cases as shown by Eva, and Alyssa decides to rewrite the square-root program with
Here is the square root procedure:
Implementing Alyssa’s version of
When Alyssa attempts to run it, since Scheme uses Applicative order evaluation, the interpreter will try to evaluate
sqrt-iter in a never ending loop because of the nature of evaluating procedures in applicative order.
What she didn’t realize is that
if is not a procedure. It is a special form which doesn’t act as a procedure underneath, and its conditions are checked first and then the clauses are implemented. Hence,
new-if won’t work the way
Exercise 1.7: Improving square root approximation
new-sqrt procedure that I mentioned above doesn’t starts failing at very large numbers, the break-point I found in my computer (with some manual binary search) was: 17738094999817, trying any number larger than that would not work as intended. This test was also true for very small numbers (having too many zeroes after the decimal point).
The alternative checks for the change of
guess. If the difference of the guess and the new guess is small enough, we can consider it a good-enough guess. This is the implementation:
This seems to work perfectly fine for very large and small numbers and it easily passes the break point. Hence, we have an improvement in our
Exercise 1.8: Cube root procedure
A rather simple exercise that asks us to implement a
cube-root procedure analogous to our new
sqrt procedure, this is based on Newton’s method for cube roots to approximate the values:
This program works well enough to calculate cube roots. No further comments.
Disclaimer: All the solutions and code provided above are solely based on the author's ideas and opinions and can be erroneous. There is no guarantee of the correctness and validity of the answers, views or code. Use them at your own risk. What works for me doesn't necessarily have to work for you.