]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_31.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex1_31.clj
1 (ns sicp.ex1_31
2   (:use [clojure.contrib test-is]
3         [sicp utils]))
4
5 (defn product [a b]
6   (if (> a b)
7     1
8     (* a (product (+ a 1) b))))
9
10 (defn prod [term a next b]
11   (if (> a b)
12     1
13     (* (term a)
14        (prod term (next a) next b))))
15
16 ;; factorial
17 ;; fact (n) = n * factorial (n - 1)
18
19 (defn factorial [n]
20   (prod identity 1 inc n))
21
22 (deftest test-factorial-of-6
23   (is (= (factorial 6)
24          (reduce * (range 1 7)))))
25
26 (deftest test-factorial-of-10
27   (is (= (factorial 10)
28          (reduce * (range 1 11)))))
29
30 (defn prod-pi [a b]
31   (prod #(/ (* % (+ % 2)) (square (+ % 1.0))) a #(+ % 2) b))
32
33 (deftest test-pi-2-digits-accuracy
34   (is (= (> (Math/abs (- 3.14159 (* 4 (prod-pi 2 1000)))) 0.001) true)))
35
36 (defn iter-prod [term a next b result]
37   (if (> a b)
38     result
39     (iter-prod term (next a) next b (* a result))))
40
41 (defn iprod [term a next b]
42   (iter-prod term a next b 1))
43
44 (deftest test-iprod-for-prod-of-1-to-10
45   (is (= (iprod identity 1 inc 10)
46          (prod identity 1 inc 10))))