Instead of spending the time to write out every SICP problem I am going to start linking to them via the html book.
The obvious problem with very small numbers and very large numbers resides in the precision of only using 0.001 as the difference validator between changes. When you get very small numbers you start getting off hundreds of percent errors, even for relatively simple squares, such as 0.0000001 and 0.0000000000001. For very large numbers you run into the same issue. In fact, the lack of appropriate precision gets so ridiculous at high numbers that often the program fails to end due to an inability to decipher the right amount of change between guesses.
(define (square x) (* x x))
(define (sqrt-iter old-guess new-guess x)
(if (good-enough? old-guess new-guess)
new-guess
(sqrt-iter new-guess (improve new-guess x)
x)))
(define (improve guess x)
(average guess (/ x guess)))
(define (average x y)
(/ (+ x y) 2))
(define (good-enough? old-guess new-guess)
(< (/ (abs (- new-guess old-guess)) new-guess) 0.0000001))
(define (sqrt x)
(sqrt-iter 0 1.0 x))
This alleviates the previous errors and gives expected results.
No comments:
Post a Comment