EDIT: I already found the bug in my code--my recursive version of cont-frac is broken. Fixed version appended to the message.
Exercise 1.38 is about approximating
e using a continued fraction expansion of
e - 2, where all the N terms are set to 1 and the D terms are a sequence as follows: 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, etc.
I wrote the following code, but it's not doing a very good job of approximating
e:
(define (cont-frac n d k) (if (= k 0) 0 (/ (n k) (+ (d k) (cont-frac n d (- k 1))))))(define (cont-frac-iter n d k) (define (iter k result) (if (= 0 k) result (iter (- k 1) (/ (n k) (+ result (d k)))))) (iter k 0))(define (calculate-e k) (define (d i) (let ((shifted-index (- i 2))) (cond ((= i 2) 2.0) ((= 0 (remainder shifted-index 3)) (+ 2.0 (* 2.0 (/ shifted-index 3.0)))) (else 1.0)))) (+ 2.0 (cont-frac (lambda (i) 1.0) d k)))
Running it with 10000 iterations:
> (calculate-e 10000)2.5000374981248825
Is something wrong with my code, or is the continued fraction approximation itself not good enough?
The problem was that my recursive cont-frac computed a different function (A continuous fraction that goes: Nk / (Dk + Nk-1 / (Dk-1 + ...)) instead of N1 / (D1 + N2 / (D2 + ...)). Fix0red:
(define (cont-frac n d k) (define (inner-cont-frac i) (if (= i k) (/ (n i) (+ (d i))) (/ (n i) (+ (d i) (inner-cont-frac (+ i 1)))))) (inner-cont-frac 1))
[Edited by - Muhammad Haggag on March 20, 2007 1:43:50 AM]