Solution to SICP Exercise 1.8

Structure and Interpretation of Computer Programs

Solution to Exercise 1.8:

(define (square x)
(* x x))

(define (cube x)
(* x x x))

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

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

(define (good-enough? guess prev-guess)
(< (/ (abs (- guess prev-guess))
guess)
0.001))

(define (cbrt x)
(cbrt-iter 1.0 0.0 x))

This solution uses the guess evaluation strategy of Exercise 1.7.

It seems to give reasonable results:

> (cbrt 8)
2.000000000012062
> (cbrt 27)
3.0000005410641766
> (cbrt 64)
4.000000000076121

Advertisements