Skip to main content
2 of 8
edited tags
Inaimathi
  • 2.2k
  • 12
  • 24

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

Given the following task:

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))
jaresty
  • 2.2k
  • 1
  • 25
  • 45