]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_38.clj
Solution to 1.38. I am generating the denominator in a little
[sicp.git] / src / sicp / ex1_38.clj
1 (ns sicp.ex1_38
2   (:use [sicp utils ex1_37]
3         [clojure.contrib test-is]))
4
5 (defn gen-sequence [len]
6   (let [l (+ 1 (int (/ len 3)))
7         s1 (map #(* % 2) (range 1 (inc l)))
8         s2 (map (fn [_] 1) (range 1 (inc l)))]
9     (concat [0 1] (interleave s1 s2 s2))))
10 ;; we concat [0 1] because nth sequences are indexed from 0 
11
12 ;; approximating e
13 (defn e-approximation [len]
14   (let [l (* 3 (int (/ len 3.0)))
15         den (gen-sequence l)]
16     (+ 2.0
17        (cont-frac (fn [k] 1.0)
18                   (fn [k] (nth den k))
19                   l))))
20
21 (comment
22 user> (e-approximation 10)
23 2.718283582089552
24 user> (e-approximation 20)
25 2.7182818284590278
26 user> (e-approximation 40)
27 2.7182818284590455
28 user> (e-approximation 50)
29 2.7182818284590455
30 user> (e-approximation 60)
31 2.7182818284590455
32 user> (e-approximation 100)
33 2.7182818284590455
34 )