sicp 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/y2. 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/y3 converge. On the other hand, if we average damp twice (i.e., use the average damp of the average damp of y x/y3) 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/yn-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.

 

通过计算,猜测求n次方根所需的平均阻尼的次数是[log2 n],[]为取整函数,据此可得代码如下:

 

 

(define (root n x)
  (my-fixed-point (lambda (t) (/ x ((exp (- n 1)) t))) 1 (floor (log2 n))))

(define (my-fixed-point f first-guess ad-time)
  (let ((eps 0.000001))
    (define (close-enough? g1 g2)
      (< (abs (- g1 g2)) eps))
    (define (try x)
      (if (close-enough? x (f x))
          x
          (try (((repeated average-damp ad-time) f) x))))
    (try first-guess)))

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

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

(define (repeated f n)
  (if (= n 1)
      f
      (composed f (repeated f (- n 1)))))

(define (composed f g)
  (lambda (x) (f (g x))))

(define (exp n)
  (if (= n 1)
      (lambda (x) x)
      (lambda (x) (* x ((exp (- n 1)) x)))))

(define (log2 x)
  (/ (log x) (log 2)))

(root 2 10.0)
(root 6 10.0)
(root 188 10.0)
(root 888 10.0)

 

 

3.162277665175675

1.467799398215191

1.0123231096741223

1.0025963668062556

你可能感兴趣的:(SICP)