29 lines
698 B
Plaintext
29 lines
698 B
Plaintext
(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)) |