From: Ramakrishnan Muthukrishnan Date: Thu, 27 May 2010 06:52:47 +0000 (+0530) Subject: worked thru parts of 1.3.4 X-Git-Url: https://git.rkrishnan.org/listings/specifications/%3C?a=commitdiff_plain;h=4deef005777d579d07885ecb96752a2a859f80a2;p=sicp.git worked thru parts of 1.3.4 --- diff --git a/src/sicp/ch1_3.clj b/src/sicp/ch1_3.clj index ebf7a20..5aaf159 100644 --- a/src/sicp/ch1_3.clj +++ b/src/sicp/ch1_3.clj @@ -92,4 +92,41 @@ ;;;=> 3.162277660168379 (mysqrt 4) ;;;=> 2.000000000000002 -) \ No newline at end of file +) + +;; section 1.3.4 +(defn average-damp [f] + (fn [x] (average x (f x)))) + +(defn new-sqrt [x] + (fixed-point (average-damp (fn [y] (/ x y))) + 1.0)) + +(defn new-cuberoot [x] + (fixed-point (average-damp (fn [y] (/ x (square y)))) + 1.0)) + +;; newton's method of root finding +;; values of x for which g(x) = 0 is the same as +;; fixed point of f(x) where f(x) = x - g(x)/Dg(x) +;; where Dg(x) is the derivative of g(x) + +(def dx 0.00001) + +(defn deriv [g] + (fn [x] (/ (- (g (+ x dx)) + (g x)) + dx))) + +(defn newton-transform [g] + (fn [x] (- x + (/ (g x) + ((deriv g) x))))) + +(defn newton-method [g guess] + (fixed-point (newton-transform g) + 1.0)) + +(defn newton-sqrt [x] + (newton-method (fn [y] (- (square y) x)) + 1.0)) \ No newline at end of file diff --git a/src/sicp/utils.clj b/src/sicp/utils.clj index 3ab538c..f5c3e9c 100644 --- a/src/sicp/utils.clj +++ b/src/sicp/utils.clj @@ -35,8 +35,9 @@ a (gcd b (rem a b)))) -(defn average [a b] - (/ (+ a b) 2.0)) +(defn average [ & coll] + (/ (reduce + coll) + (float (count coll)))) (defmacro microbench " Evaluates the expression n number of times, returning the average