2011-08-30

SICP Exercise 1.8: Cube Roots

Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value
Use this formula to implement a cube-root procedure analogous to the square-root procedure.

The sqrt procedure from last exercise is pretty close to what we require here. We just need a different implementation of improve that implements the above formula and a modified version of good-enough? that uses the cube-root version of improve to test the guesses.

I'm assuming the same definition of square from exercise 1.3. Given that, here's what I came up with:
(define (good-enough-cbrt? guess x)
  (< (abs (- guess (improve-cbrt guess x))) (/ guess 1000000)))

(define (improve-cbrt guess x)
  (/ (+ (/ x (square guess)) (* 2 guess)) 3))

(define (cbrt-iter guess x)
  (if (good-enough-cbrt? guess x)
      guess
      (cbrt-iter (improve-cbrt guess x)
                 x)))

(define (cbrt x) (cbrt-iter 1.0 x))
And here's it in use:
> (cbrt (* 3 3 3))
3.0000005410641766
> (cbrt 0.5)
0.7937005260076354
> (* (cbrt 0.5) (cbrt 0.5) (cbrt 0.5))
0.5000000000444796

No comments:

Post a Comment