Never been to DZone Snippets before?

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

About this user

Alexandru Scvortov

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Square root in Scheme

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
...

   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)


« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS