exercise 1.8 solution.
authorRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Thu, 25 Mar 2010 03:27:04 +0000 (08:57 +0530)
committerRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Thu, 25 Mar 2010 03:27:04 +0000 (08:57 +0530)
chapter1/ch1_1.clj

index bcb63291c33b23444fc42923ce751b471e1dad2d..118022ecf9a3a0a2abae4b67dc7a47cff48e4375 100644 (file)
@@ -235,4 +235,30 @@ user> (sqrt 9)
 user> (sqrt 81)
 9.000000000007091
 
-;; exercise 1.8:
+;; exercise 1.8: cube root
+(defn cube [x]
+  (* x x x))
+
+(defn improve [guess x]
+  (/ (+ (/ x (square guess)) (* 2 guess)) 3))
+
+(defn cubert-iter [old-guess new-guess x]
+  (if (good-enough? old-guess new-guess x)
+    new-guess
+    (cubert-iter new-guess (improve new-guess x)
+                x)))
+
+(defn cubert [x]
+  (cubert-iter x 1.0 x))
+
+user> (cubert (cube 2))
+2.000000000012062
+user> (cubert (cube 10))
+10.000000000000002
+user> (cubert (cube 9))
+9.000000000053902
+user> (cubert (cube 0.001))
+0.001000000000000962
+user> (cubert (cube 0.0001))
+1.000000000000001E-4
+user> 
\ No newline at end of file