Exploring SICP
Sunday, April 30th, 2006This book totally rocks. And it kinda makes me depressed. Some exercises are really tough, and it’s putting me through all kinds of grief. But heck, I’m getting a kick out of learning this stuff. Kinda like going back to college and getting all the stuff right. But you need to have a lot of patience. You need to unlearn some concepts. Anyways, to console myself, I have done one of the easier exercises (1.8). Here’s how you calculate a cube root (apologies to non-geeks – the posts in the coming days/weeks would be full of this):
(define (cuberoot-iter guess x)
(if (good-enough? guess x)
guess
(cuberoot-iter (improve guess x)
x)))
(define (improve guess x)
(/ (+ (/ x (square guess)) (* 2 guess)) 3))
(define (good-enough? guess x)
(< (abs (- (cubed guess) x)) 0.001))
(define (cubed x)
(* x (* x x)))
(define (cuberoot x)
(cuberoot-iter 1.0 x))
Evals to (using mit-scheme):
(cuberoot 27)
;Value: 3.0000005410641766