1.37 Exercise 1.37
A procedure for evaluating a continued fraction for up to depth k:
(define (cont-frac n d k) | (define (loop i) | (if (= i k) (/ (n i) (d i)) | (/ (n i) | (+ (d i) (loop (+ i 1)))))) | (loop 1)) |
|
Using an auxiliary procedure test-37, we can see 1/phi being approximated:
(define (test-37 k) | (/ 1 (cont-frac (lambda (i) 1.0) | (lambda (i) 1.0) | k))) |
|
> (test-37 10) |
1.6181818181818184 |
> (test-37 100) |
1.618033988749895 |
Writing an iterative cont-frac procedure is difficult until you
realize that it is much easier to create the fraction from the inside
out, starting from k and moving to 1. Then the answer is
straightforward:
(define (cont-frac n d k) | (define (loop current i) | (if (= i 0) current | (loop (/ (n i) (+ (d i) current)) | (- i 1)))) | (loop (/ (n k) (d k)) (- k 1))) |
|