1
\$\begingroup\$

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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 31, 2011 at 2:52
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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)))
answered Mar 31, 2011 at 11:55
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.