Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 1.08

From Drewiki
Jump to: navigation, search

Problem

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

<math>\frac{{x}/{y^2} + 2y}{3}</math>

Use this formula to implement a cube-root procedure analogous to the square-root procedure from section 1.1.7 of the text.

Solution

Here's a straightforward solution to the problem.

(define (square x) (* x x))
 
(define (cube x) (* (square x) x))
 
(define (cube-root-iter guess x)
  (if (good-enough? guess x)
      guess
      (cube-root-iter (improve guess x)
                      x)))
 
(define (improve guess x)
  (/
   (+ (/ x (square guess))
      (* 2 guess))
   3))
 
(define (good-enough? guess x)
  (< (abs (- (cube guess) x)) 0.001))

Tests

(cube-root-iter 1 8)

Output:

2.0000049116755


(cube-root-iter 1 27)

Output:

3.00000054106418


(cube-root-iter 1 64)

Output:

4.00001744951074


(cube-root-iter 1 125)

Output:

5.00000000028793


(cube-root-iter 1 100)

Output:

4.64159011104646
Personal tools