例子:求2的平方根
Guess |
Quotient |
Average |
|
1 |
(2/1) = 2 |
((2 + 1)/2) = 1.5 |
|
1.5 |
(2/1.5) = 1.3333 |
((1.3333 + 1.5)/2) = 1.4167 |
|
1.4167 |
(2/1.4167) = 1.4118 |
((1.4167 + 1.4118)/2) = 1.4142 |
|
1.4142 |
...
|
...
|
一.给出一个scheme的过程 (define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x))) 二.改进猜的数(x除以猜的数和猜的数的平均值 (define (average x y)
(/ (+ x y) 2)) (define (improve guess x)
(average guess (/ x guess))) 三.如何得到比较适合的值.这里做了一个假设,猜的值的平方减去x不小于0.001 (define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
注:如何用内部过程来使用上面的部分: (define (sqrt x) (define (good-enough? guess) (define (square) (* guess guess)) (< (abs (- (square) x)) 0.001)) (define (improve guess) (define (average y) (/ (+ guess y) 2)) (average (/ x guess))) (define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess)))) (sqrt-iter 1.0))
|