1.7
较小的数,
(sqrt 0.0004) ;
(sqrt 0.0004) ; 0.0354008825558513
(square (sqrt 0.0004)) ; 0.0012532224857331766
;这个结果 guess平方 与 x 的差 大于 0.001,已经不满足了 good-enough? 的检查了
复制代码
较大的数,
(sqrt 12345678901234) 就算不出了,
因为 scheme 能表示的小数精度有限,在某个时候, (square guess) 与 x 之差还是大于 0.001, 因为精度有限,连续的两个 guess 之间的差太小了, improve 就没法产生改进的 guess 了,只能陷入无限循环,永远也算不出。
新的 good-enough? 函数:
(define (good-enough? previous guess)
(< (/ (abs (- previous guess)) guess) 0.0000000001))
复制代码
新的 sqrt-iter
(define (sqrt-iter guess x)
(if (good-enough? guess (improve guess x))
guess
(sqrt-iter (improve guess x) x)))
复制代码
整个:
#lang sicp
(define (square x) (* x x))
(define (good-enough? previous guess)
(< (/ (abs (- previous guess)) guess) 0.0000000001))
(define (sqrt-iter guess x)
(if (good-enough? guess (improve guess x))
guess
(sqrt-iter (improve guess x) x)))
(define (improve guess x)
(average guess (/ x guess)))
(define (average x y)
(/ (+ x y) 2))
(define (sqrt x)
(sqrt-iter 1.0 x))
复制代码
评论