]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_45.clj
solutions to 4.35, 4.36 and 4.37
[sicp.git] / src / sicp / ex1_45.clj
1 (ns sicp.ex1_45
2   (:use [clojure.contrib test-is]
3         [sicp utils]
4         [sicp ch1_3]
5         [sicp ex1_43]))
6
7 (defn nthroot [x n]
8   (fixed-point ((repeated average-damp
9                           (int (/ (Math/log n) (Math/log 2)))) 
10                 (fn [y] (/ x (Math/pow y (- n 1)))))
11                1.0))
12
13 ;; experiments show that average damp needs to e applied log2n times.
14 (comment
15 user> (nthroot (* 3 3 3) 3)
16 ;;=> 2.9999972321057697
17 user> (nthroot (* 3 3 3 3) 4)
18 ; Evaluation aborted.
19 user> (use 'sicp.ex1_45 :reload)
20 ;;=> nil
21 user> (nthroot (* 3 3 3 3) 4)
22 ;;=> 3.000000000000033
23 user> (nthroot (* 3 3 3 3 3) 5)
24 ;;=> 3.0000008877496294
25 user> (nthroot (* 3 3 3 3 3 3) 5)
26 ;;=> 3.737194011460545
27 user> (nthroot (* 3 3 3 3 3 3) 6)
28 ;;=> 2.999996785898161
29 user> (nthroot (* 3 3 3 3 3 3 3) 7)
30 ;;=> 3.0000041735235947
31 user> (nthroot (* 3 3 3 3 3 3 3 3) 8)
32 ;;=> ; Evaluation aborted.
33 user> (use 'sicp.ex1_45 :reload)
34 ;;=> nil
35 user> (nthroot (* 3 3 3 3 3 3 3 3) 8)
36 ;;=> 3.0000000000173292
37 user> (nthroot (* 3 3 3 3 3 3 3 3 3 3 3 3 3 3) 14)
38 ;;=> 2.9999959148601363
39 user> (nthroot (* 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3) 15)
40 ;;=> 3.000004202219401
41 user> (nthroot (* 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3) 16)
42 ;;=> ; Evaluation aborted.
43 user> (Math/log2 10)
44 ;;=> ; Evaluation aborted.
45 user> (/ (Math/log 10) (Math/log 2))
46 ;;=> 3.3219280948873626
47 user> (/ (Math/log 16) (Math/log 2))
48 ;;=> 4.0
49 user> (use 'sicp.ex1_45 :reload)
50 ;;=> nil
51 user> (nthroot (* 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3) 16)
52 ;;=> 3.0
53 user> (nthroot (Math/pow 3 16) 16)
54 ;;=> 3.0
55 user> (nthroot (Math/pow 3 35) 35)
56 ;;=> 3.000000146591681
57 user> (nthroot (Math/pow 3 50) 50)
58 ;;=> 2.9999967255008917
59 user>   
60 )