]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_46.clj
solution to 1.46
[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)))
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 (comment
25 (sqrt 4)
26 ;;=> 3.9999942779541016
27 user> (sqrt (* 2 2))
28 ;;=> 3.9999942779541016
29 user> (fixed-point #(Math/cos %) 1.0)
30 ;;=> 0.7390822985224024
31 user> (fixed-point #(+ (Math/cos %) (Math/sin %)) 1.0)
32 ;;=> 1.2587315962971173  
33 )