my attempt to do the exercises in sicp.

Tuesday, July 1, 2008

sicp exercise 1.38



;  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.



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


(define (ones i) 1)
(define (double i) (* i 2))
(define (scale proc n factor def)
   (if (= (remainder (+ n 1) factor) 0)
       (proc (quotient (+ n 1) factor))
       (def n)))

(define (d n) (scale double n 3 ones))

(display (cont-frac-iter (lambda(i) 1.0) d 1000))(newline)

; Answer: 0.718281828459045


No comments: