Exercise 1.7

The Question

The good-enough? test used in computing square roots will not be very effective for finding the square roots of very small numbers. Also, in real computers, arithmetic operations are almost always performed with limited precision. This makes our test inadequate for very large numbers. Explain these statements, with examples showing how the test fails for small and large numbers. An alternative strategy for implementing good-enough? is to watch how guess changes from one iteration to the next and to stop when the change is a very small fraction of the guess. Design a square-root procedure that uses this kind of end test. Does this work better for small and large numbers?

The Answer

We want to stop once guessing once the guess only changes by a very small fraction of the guess. We can do this by comparing the fraction of the change by the guess with the fraction by which we want to stop. We will also wrap the change with abs because we do not know if the guess increases or decreases:

(define (good-enough? guess new-guess)
  (< (/ (abs (- new-guess guess)) guess) 0.0001))

Since we do not want to call improve twice - once for good-enough? and once for sqrt-iter, we'll calculate the new guess once and pass both the old guess and the new guess to sqrt-iter:

(define (sqrt-iter guess new-guess x)
  (if (good-enough? guess new-guess)
      guess
      (sqrt-iter new-guess (improve new-guess x) x)))

We can now define sqrt and the other helper procedures:

(define (sqrt x)
  (sqrt-iter 1.0 (improve 1.0 x) x))

(define (improve guess x)
  (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))

Taking our new sqrt-iter for a spin, we get consistent, if not better results:

(sqrt 3)
1.7321428571428572
(sqrt (+ 100 37))
11.705105833379696
(sqrt (+ (sqrt 2) (sqrt 3)))
1.7739279023207892
(define (square x) (* x x))
(square (sqrt 1000))
1000.000369924366

Judging by the results, the two approaches are equally good.

Comments