Initial commit
This commit is contained in:
parent
605eae2a5d
commit
fab6abd81b
29
SICP/exercise_1_40.janet
Normal file
29
SICP/exercise_1_40.janet
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
(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 (* 0.5 (+ guess (f guess)))]
|
||||||
|
(if (close-enough? guess next)
|
||||||
|
next
|
||||||
|
(try-it next))))
|
||||||
|
(try-it first-guess))
|
||||||
|
|
||||||
|
(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 newtons-method [g guess]
|
||||||
|
(fixed-point (newton-transform g) guess))
|
||||||
|
|
||||||
|
(defn cubic [a b c]
|
||||||
|
(fn [x]
|
||||||
|
(let [cub (* x x x)
|
||||||
|
qua (* a x x)
|
||||||
|
sing (* b x)]
|
||||||
|
(+ cub qua sing c))))
|
||||||
|
|
||||||
|
(print (newtons-method (cubic 5 3 -1) -10))
|
||||||
Loading…
Reference in New Issue
Block a user