my attempt to do the exercises in sicp.

Friday, July 4, 2008

sicp exercise 1.46


;  Exercise 1.46.  Several of the numerical methods described in this chapter are instances of an extremely
;  general computational strategy known as iterative improvement. Iterative improvement says that, to
;  compute something, we start with an initial guess for the answer, test if the guess is good enough,
;  and otherwise improve the guess and continue the process using the improved guess as the new guess.
;  Write a procedure iterative-improve that takes two procedures as arguments: a method for telling whether
;  a guess is good enough and a method for improving a guess. Iterative-improve should return as its value
;  a procedure that takes a guess as argument and keeps improving the guess until it is good enough. Rewrite
;  the sqrt procedure of section 1.1.7 and the fixed-point procedure of section 1.3.3 in terms of
;  iterative-improve.



(define (iterative-improve good-enough? improve-guess)
  (lambda (x)
    (define (iter guess)
      (let ((improved-guess (improve-guess guess)))
      (if (good-enough? guess improved-guess)
          guess
          (iter improved-guess))))
      (iter x)))

(define tolerance 0.00001)
(define (close-enough? v1 v2)
  (< (abs (- v1 v2)) tolerance))

(define (fixed-point f first-guess)
  ((iterative-improve close-enough? f) first-guess))

(define (sqrt-iter guess x)
  (if (close-enough? guess x)
      guess
      (sqrt-iter (improve guess x) x)))

;(define (average x y) (/ (+ x y) 2))
(define (sqrt x)
  ((iterative-improve close-enough? (lambda(y) (/ (+ y (/ x y)) 2))) 1.0))


(display (sqrt 4))(newline)
(display (sqrt 300))(newline)
(display (sqrt 237))(newline)
(display (sqrt 2000000000))(newline)
(display (sqrt 4.49999999))(newline)


No comments: