Compute e using Euler's expansion

Given the following task:

Exercise 1.38. 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 Ni are all 1, and the Di 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.

I wrote this solution:

(define (i-cont-frac n d k)
(define (iterate result i)
(define (next n) (- n 1))
(if (= i 0) result
(iterate (/ (n i)
(+ (d i)
result)) (next i))))
(iterate 0 k))

(define (divisible? a b) (= (remainder a b) 0))
(define (compute-e k)
(define (n i) 1)
(define (d i) (cond ((= i 1) 1)
((= i 2) 2)
((divisible? (- i 1) 3)
(* (/ (- i 1) 3.0) 2.0))
(else 1.0)))
(+ 2 (cont-frac n d k)))


What do you think?

Your definition of d is not quite right. It produces incorrect results for some values of i and it has two special cases which are not necessary. A possible definition is:

  (define (d i)
(cond
((divisible? (+ i 1) 3)
(* (/ (+ i 1) 3) 2))
(else 1)))


This is because i is 1-indexed (series begins with i = 1). If you want a decimal instead of a fraction as your result, change the multiplier to 2.0 and the else value to 1.0.

Another way to write d is:

  (define (d i)
(let
((d-value (* (/ (+ i 1) 3) 2)))
(if (integer? d-value) d-value 1)))