Exercise1-37 <---> Exercise1-39

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.


Scheme solution:

(define (euler k)
  (define (d i)
    (if (= (modulo (1+ i) 3) 0)
        (* (/ (1+ i) 3) 2.0)
        1.0))
  (+ 2.0 (cont-frac (lambda (i) 1.0) d k)))

Haskell solution:

euler k = 2 + cont'frac (const 1) d k
  where d i | (i+1) `mod` 3 == 0 = 2 * fromIntegral (i+1) / 3
            | otherwise          = 1

Exercise1-37 <---> Exercise1-39


Comments

As I see it this is a perfect time to use "let"...

The solutions are the same of course.

 (define (euler x)
   (define (d i)
     (let ((index (/ (+ i 1) 3)))
       (if (integer? index)
           (* 2 index)
           1)))
  (+ 2.0
     (cont-frac (lambda (i) 1) d x)))
Posted by DanielMoerner at 2008-12-25 07:35:21

:) :)) :( ;) :\ |) X-( B) Markup

Exercise1-38 (last edited 2008-10-03 22:50:39 by FirstnameLastname)