]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_46.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex1_46.clj
1 (ns sicp.ex1_46
2   (:use [clojure.contrib test-is]
3         [sicp utils]))
4
5 (defn iterative-improve [good-enough-fn? improve-guess-fn]
6   (fn [guess]
7     (let [new-guess (improve-guess-fn guess)]
8       (if (good-enough-fn? guess new-guess)
9         new-guess
10         (recur new-guess)))))
11
12 (defn sqrt [x]
13   (let [initial-guess 1.0]
14     ((iterative-improve
15       (fn [old new] (< (Math/abs (- old new)) 0.00001))
16       (fn [guess] (average guess (/ x guess))))
17      initial-guess)))
18
19 (defn fixed-point [f initial-guess]
20   ((iterative-improve
21     (fn [old new] (< (Math/abs (- old new)) 0.00001))
22     f) initial-guess))
23
24 (deftest test-sqrt-4
25   (is #(< (Math/abs (- (sqrt 4) (Math/sqrt 4))) 0.00001)))
26
27 (deftest test-sqrt-10
28   (is #(< (Math/abs (- (sqrt 10) (Math/sqrt 10))) 0.00001)))
29
30 (deftest test-fixed-point-cos
31   (is (fn [_] (< (Math/abs (- (fixed-point #(Math/cos %) 1.0)
32                               0.7390822))
33                  0.00001))))
34
35 (deftest test-fixed-point-cos-plus-sin
36   (is (fn [_] (< (Math/abs (- (fixed-point #(+ (Math/cos %) (Math/sin %)) 1.0)
37                               1.258731))
38                  0.00001))))
39
40
41
42 (comment
43 user> (fixed-point #(Math/cos %) 1.0)
44 ;;=> 0.7390822985224024
45 user> (fixed-point #(+ (Math/cos %) (Math/sin %)) 1.0)
46 ;;=> 1.2587315962971173  
47 )
48