3 [clojure.contrib test-is]))
5 ;; 1.3.1: Procedures as arguments
6 (defn sum-integers [a b]
9 (+ a (sum-integers (+ a 1) b))))
14 (+ (cube a) (sum-cubes (+ a 1) b))))
19 (+ (/ 1.0 (* a (+ a 2))) (pi-sum (+ a 1) b))))
21 (defn sum [term a next b]
25 (sum term (next a) next b))))
27 (def sum-cubes-new (fn[a b] (sum cube a inc b)))
29 (deftest test-sum-of-first-10-integers
30 (is (sum #(identity %) 1 inc 10) 55))
32 ;; (* (sum #(/ 1.0 (* % (+ % 2))) 1 #(+ % 4) 1000) 8)
33 ;;=> 3.139592655589783 (approaches PI)
35 (defn integral [f a b dx]
36 (* (sum f (+ a (/ dx 2)) #(+ % dx) b)
39 (integral cube 0 1 0.001)
41 (integral cube 0 1 0.005)
42 ;;=>0.24999687500000028
45 (defn close-enough? [x y tolerance]
46 (< (abs (- x y)) tolerance))
48 (defn search [f neg-point pos-point]
49 (let [mid-point (average neg-point pos-point)]
50 (if (close-enough? neg-point pos-point 0.001)
52 (let [test-value (f mid-point)]
53 (cond (pos? test-value) (search f neg-point mid-point)
54 (neg? test-value) (search f mid-point pos-point)
57 (defn half-interval-method [f a b]
60 (cond (and (neg? a-val) (pos? b-val)) (search f a b)
61 (and (pos? a-val) (neg? b-val)) (search f b a)
62 :else (str "values are not of opposite sign"))))
65 (half-interval-method #(Math/sin %) 2.0 4.0)
67 (half-interval-method (fn [x] (- (* x x x) (* 2 x) 3)) 1.0 2.0)
71 ;;; fixed point of a function
72 (defn fixed-point [f guess]
74 (if (close-enough? next guess 0.00001)
76 (fixed-point f next))))
79 (fixed-point #(Math/cos %) 1.0)
80 ;;;=> 0.7390822985224024
81 (fixed-point #(+ (Math/cos %) (Math/sin %)) 1.0)
82 ;;;=> 1.2587315962971173
85 ;; sqrt as fixed point of y/x
87 (fixed-point (fn [y] (average y (/ x y)))
92 ;;;=> 3.162277660168379
94 ;;;=> 2.000000000000002
98 (defn average-damp [f]
99 (fn [x] (average x (f x))))
102 (fixed-point (average-damp (fn [y] (/ x y)))
105 (defn new-cuberoot [x]
106 (fixed-point (average-damp (fn [y] (/ x (square y))))
109 ;; newton's method of root finding
110 ;; values of x for which g(x) = 0 is the same as
111 ;; fixed point of f(x) where f(x) = x - g(x)/Dg(x)
112 ;; where Dg(x) is the derivative of g(x)
117 (fn [x] (/ (- (g (+ x dx))
121 (defn newton-transform [g]
126 (defn newton-method [g guess]
127 (fixed-point (newton-transform g)
130 (defn newton-sqrt [x]
131 (newton-method (fn [y] (- (square y) x))
134 (defn fixed-point-of-transform [g transform guess]
135 (fixed-point (transform g) guess))
138 (fixed-point-of-transform (fn [y] (/ x y))
143 (fixed-point-of-transform (fn [y] (- (square y) x))