my attempt to do the exercises in sicp.

Friday, July 4, 2008

sicp exercise 1.45

;  Exercise 1.45.  We saw in section 1.3.3 that attempting to compute square roots by naively finding a
;  fixed point of y -> x/y does not converge, and that this can be fixed by average damping. The same
;  method works for finding cube roots as fixed points of the average-damped y -> x/y^2. Unfortunately,
;  the process does not work for fourth roots -- a single average damp is not enough to make a fixed-point
;  search for y -> x/y^3 converge. On the other hand, if we average damp twice (i.e., use the average damp
;  of the average damp of y -> x/y^3) the fixed-point search does converge. Do some experiments to
;  determine how many average damps are required to compute nth roots as a fixed-point search based upon
;  repeated average damping of y -> x/y^(n-1). Use this to implement a simple procedure for computing nth
;  roots using fixed-point, average-damp, and the repeated procedure of exercise 1.43. Assume that any
;  arithmetic operations you need are available as primitives.

(define tolerance 0.00001)

(define (fixed-point f first-guess)
  (define (close-enough? v1 v2)
    (< (abs (- v1 v2)) tolerance))
  (define (try guess)
    (display guess)(newline)
    (let ((next (f guess)))
      (if (close-enough? guess next)
           (try next))))
   (try first-guess))

(define (average x y) (/ (+ x y) 2))

(define (compose f g)
    (f (g x))))

(define (repeated f n)
  (define (iter i res)
    (if (>= i n)
        (iter (+ i 1) (compose f res))))
  (iter 1 f))

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

(define (fast-exp-iter base exp)
  (define (func n b res)
    (cond ((= n 0) res)
          ((even? n) (func (/ n 2) (square b) res))
          (else (func (- n 1) b (* res b)))))
    (func exp base 1))

(define (average-damp f)
    (average x (f x))))

(define (func x n)
    (/ x (fast-exp-iter y (- n 1)))))

; nth root is the fixed-point of the function func
(define (nth-root x n)
  (fixed-point (repeated (average-damp (func x n)) 5) 3.0))

(display (nth-root 256 8))(newline)

No comments: