]> git.rkrishnan.org Git - sicp.git/blobdiff - src/sicp/ch1_3.clj
Solutions to 4.27, 4.28 and 4.29.
[sicp.git] / src / sicp / ch1_3.clj
index ebf7a20d770d811b10a2bfee98efed89c5397e1f..355cdc416f5f978cffac121376fcda5606a01054 100644 (file)
 ;;;=> 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))
+
+(defn fixed-point-of-transform [g transform guess]
+  (fixed-point (transform g) guess))
+
+(defn sqrt1 [x]
+  (fixed-point-of-transform (fn [y] (/ x y))
+                           average-damp
+                           1.0))
+
+(defn sqrt2 [x]
+  (fixed-point-of-transform (fn [y] (- (square y) x))
+                           newton-transform
+                           1.0))
\ No newline at end of file