Exercise 1.7.  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?

 

Solution:


(define (square x) (* x x))
(define
(average x y)
(/
(+ x y)
2))
(define
(good-enough?
x
guess)
(<
(abs
(-
x
(square guess)))
0.00001))
(define
(good-enough2?
x
guess)
(<
(abs
(-
x
guess))
0.00001))
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x))))
(define
(improve-guess
x
guess)
(average
(/
x
guess)
guess))
(define
(sqrt-iter x guess)
(if
(or
(good-enough?
x
guess)
(good-enough2?
guess
(improve-guess
x
guess)))
guess
(sqrt-iter
x
(improve-guess
x
guess)))))
(define (sqrt x) (sqrt-iter x 1.0))

 


Comments

Leave a Reply

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading