Initial commit
This commit is contained in:
parent
9bbad1be58
commit
41b9ad7696
66
SICP/exercise_1_45.janet
Normal file
66
SICP/exercise_1_45.janet
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
(def tolerance 0.00001)
|
||||||
|
|
||||||
|
(defn fixed-point [f first-guess]
|
||||||
|
(defn close-enough? [v1 v2]
|
||||||
|
(< (math/abs (- v1 v2))
|
||||||
|
tolerance))
|
||||||
|
(defn try-it [guess]
|
||||||
|
(let [next (f guess)]
|
||||||
|
(if (close-enough? guess next)
|
||||||
|
next
|
||||||
|
(try-it next))))
|
||||||
|
(try-it first-guess))
|
||||||
|
|
||||||
|
(defn compose [f g]
|
||||||
|
(fn [x] (f (g x))))
|
||||||
|
|
||||||
|
(defn repeated [f n]
|
||||||
|
(defn iter [inner_f k]
|
||||||
|
(cond
|
||||||
|
(= k 1) inner_f
|
||||||
|
(iter (compose f inner_f) (- k 1))))
|
||||||
|
(iter f n))
|
||||||
|
|
||||||
|
(defn average-damp [f]
|
||||||
|
(fn [x] (* 0.5 (+ x (f x)))))
|
||||||
|
|
||||||
|
(defn nth-root [n x]
|
||||||
|
(fn [y]
|
||||||
|
(defn iter [k state]
|
||||||
|
(cond
|
||||||
|
(= k 2) (/ x state)
|
||||||
|
(iter (- k 1) (* state y))))
|
||||||
|
(iter n y)))
|
||||||
|
|
||||||
|
(defn root [n x]
|
||||||
|
(def damping-count (math/floor (/ (math/log n) (math/log 2))))
|
||||||
|
((repeated average-damp damping-count) (nth-root n x)))
|
||||||
|
|
||||||
|
(defn pow [n x]
|
||||||
|
(defn iter [k state]
|
||||||
|
(cond
|
||||||
|
(= k 1) state
|
||||||
|
(iter (- k 1) (* state x))))
|
||||||
|
(iter n x))
|
||||||
|
|
||||||
|
(var i 2)
|
||||||
|
(while (< i 100)
|
||||||
|
(def result (fixed-point (root i 12312.0) 1.0))
|
||||||
|
(printf "%d,%f: 12312.0 = %f" i result (pow i result))
|
||||||
|
(set i (inc i)))
|
||||||
|
|
||||||
|
# 2th-root, 1 damping
|
||||||
|
# 3rd-root, 1 damping
|
||||||
|
# 4th-root, 2 damping
|
||||||
|
# 5th-root, 2 damping
|
||||||
|
# 6th-root, 2 damping
|
||||||
|
# 7th-root, 2 damping
|
||||||
|
# 8th-root, 3 damping
|
||||||
|
# 9th-root, 3 damping
|
||||||
|
# 10th-root, 3 damping
|
||||||
|
# 11th-root, 3 damping
|
||||||
|
# 12th-root, 3 damping
|
||||||
|
# 13th-root, 3 damping
|
||||||
|
# 14th-root, 3 damping
|
||||||
|
# 15th-root, 3 damping
|
||||||
|
# 16th-root, 4 damping
|
||||||
Loading…
Reference in New Issue
Block a user