Initial commit
This commit is contained in:
parent
41b9ad7696
commit
cb384b6b7e
34
SICP/exercise_1_46.janet
Normal file
34
SICP/exercise_1_46.janet
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
(defn iterative-improve [good-enough? next]
|
||||
(fn [guess]
|
||||
(defn iter [prev current]
|
||||
(cond
|
||||
(good-enough? prev current) current
|
||||
(iter current (next current))))
|
||||
(iter guess (next guess))))
|
||||
|
||||
(def tolerance 0.0001)
|
||||
(defn good-enough? [prev current]
|
||||
(< (math/abs (- prev current))
|
||||
tolerance))
|
||||
|
||||
(defn improve-sqrt [x]
|
||||
(fn [y] (/ x y)))
|
||||
|
||||
(defn average-damp [f]
|
||||
(fn [x] (* 0.5 (+ x (f x)))))
|
||||
|
||||
(defn improve [x] (average-damp (improve-sqrt x)))
|
||||
|
||||
(defn sqrt [x]
|
||||
(def run (iterative-improve good-enough? (improve x)))
|
||||
(run 1.0))
|
||||
|
||||
(defn fixed-point [f initial-guess]
|
||||
(def run (iterative-improve good-enough? f))
|
||||
(run initial-guess))
|
||||
|
||||
(defn fix-sqrt [x]
|
||||
(fixed-point (improve x) 1.0))
|
||||
|
||||
(print (sqrt 5.0))
|
||||
(print (fix-sqrt 5.0))
|
||||
Loading…
Reference in New Issue
Block a user