# Use Newton's Method to compute sqrt(x)

Use Newton's method to compute the square root of a number. Newton's method involves successive approximation. You start with a guess, and then continue averaging successive guesses until you reach a satisfactory level of precision.

I wrote the following (rough) solution in Scheme. Can you help me make it better?

(define (abs x) ((if (< x 0) - +)  x))
(define (almost-equal x y delta)
(> delta (abs (- x y))))

(define (sqrt-prime x last-x)
(let ((next-x (/ (+ x last-x) 2)))
(if (almost-equal next-x x 0.000001) x
(sqrt-prime next-x x))))

(define (sqrt x) (sqrt-prime x 1))


The sqrt-prime function neither needs nor uses the last-guess argument. It can be safely eliminated:

(define (sqrt-prime guess x)
(if (good-enough? guess x) guess
(sqrt-prime (better-guess guess x) x)))


You may call the function thus:

(define (sqrt x) (sqrt-prime 1.0 x))


I feel that, other than this minor change, your program is succinct enough.

• Good point. I got some good feedback on (cuberoot ...) so I'm changing this quite a bit, but otherwise I'd definitely fix it - thanks! – jaresty Mar 24 '11 at 2:02

abs is mentioned in R6RS, so I'm inclined to believe that you can treat it as a primitive.

The scheme convention is to end predicates with ?, so that should really be almost-equal?