SICP Exercise 1.38

Question

In 1737, the Swiss mathematician Leonhard Euler published a memoir De Fractionibus Continuis, which included a continued fraction expansion for \(e−2\), where \(e\) is the base of the natural logarithms. In this fraction, the \(N_i\) are all 1, and the \(D_i\) are successively 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, …. Write a program that uses your cont-frac procedure from exercise 1.37 to approximate \(e\), based on Euler’s expansion.

Answer

The equation that I used for coming up with \(D_i\) works as follows.

First of all, if \(i-2\) is not divisible by 3, return 1. If it is divisible, return \((2\cdot\frac{i-2}{3})+2\).

So, here is the full code. Again, we need surprisingly few iterations (only 7) to get to an accuracy of 4 decimal places (\(2.7183\)).

(define (d i)
  (if (not (= 0
              (remainder (- i 2) 3))) 1
      (+ 2 (* 2 (/ (- i 2) 3)))))


(define (cont-frac n d k)
  (define (iterate counter)
    (if (= k counter) (/ (n k) (d k))
      (/ (n counter) (+ (d counter) (iterate (+ counter 1))))))
  (iterate 1))

(+ 2 (cont-frac (λ (i) 1.0)
           d
           7))

Result:

2.7183098591549295