DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

This implements a square root function in Scheme using Newton's approximation algorithm. 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 ...

(define (sqrt-iter guess x) (if (good-enough? 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 (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (sqrt x) (sqrt-iter 1.0 x)) (sqrt 10)