]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_38.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[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 (defn den-seq [k]
13   (if (= (rem k 3) 2)
14     (* (/ (+ k 1) 3) 2) ;; ((k+1)/3)*2
15     1))
16
17 ;; approximating e
18 (defn e-approximation [len]
19   (+ 2.0
20      (cont-frac (fn [k] 1.0)
21                 (fn [k] (den-seq k))
22                 len)))
23
24 (comment
25 user> (e-approximation 10)
26 2.718283582089552
27 user> (e-approximation 20)
28 2.7182818284590278
29 user> (e-approximation 40)
30 2.7182818284590455
31 user> (e-approximation 50)
32 2.7182818284590455
33 user> (e-approximation 60)
34 2.7182818284590455
35 user> (e-approximation 100)
36 2.7182818284590455
37 )
38