Square root in Scheme
Basically, if you want the square root of y and your best guess is x, a better guess is the average of x and y/x.
So, if you want the square root of 10 and your best guess is 3,
x=3 y=10 x<-(3 + 10/3)/2
x=3.166 y=10 x<-(3.166 + 10/3.133)/2
x=3.162
...
1 2 (define (sqrt-iter guess x) 3 (if (good-enough? guess x) 4 guess 5 (sqrt-iter (improve guess x) 6 x))) 7 8 (define (improve guess x) 9 (average guess (/ x guess))) 10 11 (define (average x y) 12 (/ (+ x y) 2)) 13 14 (define (good-enough? guess x) 15 (< (abs (- (square guess) x)) 16 0.001)) 17 18 (define (sqrt x) 19 (sqrt-iter 1.0 x)) 20 21 (sqrt 10)