HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Use Newton's Method to compute sqrt(x)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodcomputesqrtnewtonuse

Problem

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 ( 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))

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#1396, answer score: 5

Revisions (0)

No revisions yet.