Exercise 1.45: We saw in 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 . Unfortunately, the process does not work for fourth roots—a single average damp is not enough to make a fixed-point search for converge. On the other hand, if we average damp twice (i.e., use the average damp of the average damp of ) 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 . 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) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess))
(define (average x y) (/ (+ x y) 2)) (define (average-damp f) (lambda (x) (average x (f x))))
(define (compose f g) (lambda (x) (f (g x)))) (define (square x) (* x x)) (define (repeated op n) (if (= n 0) (lambda (x) x) (compose op (repeated op (- n 1))))) ((repeated square 2) 5)
(define (pow x n) (if (= n 0) 1 (* x (pow x (- n 1))))) (define (n-th-root x n) (fixed-point (average-damp (lambda (y) (/ x (pow y (- n 1))))) 1)) (n-th-root 9 2)
Given The above implementation,
(n-th-root 16 4) will make the page NOT responding!
repeated average-damp twice will make (n-th-root 16 4) work
(define (pow x n) (if (= n 0) 1 (* x (pow x (- n 1))))) (define (n-th-root x n) (fixed-point ((repeated average-damp 2) (lambda (y) (/ x (pow y (- n 1))))) 1)) (n-th-root 16 4)
The above implementation will make (n-th-root 666 8) freeze the page!
Guess that repeated average-damp n/2 times will make (n-th-root x n) work
(define (pow x n) (if (= n 0) 1 (* x (pow x (- n 1))))) (define (n-th-root x n) (fixed-point ((repeated average-damp (floor (/ n 2))) (lambda (y) (/ x (pow y (- n 1))))) 1)) (n-th-root 666 8)