Created
March 4, 2013 12:54
-
-
Save ibigbug/5082063 to your computer and use it in GitHub Desktop.
Dichotomy theorems in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn F [a b c]; generate the target function | |
(fn [x] | |
(+ (* (+ (* a x) b) x) c))) | |
(def f1 (F 1 2 1)) | |
(defn | |
^{:doc "(Solve f a b) | |
f-- the target function | |
a,b the interval for isolating the root" | |
:user/comment "Dichotomy theorems in Clojure" | |
:test (fn [] | |
(assert (> (Solve f1 -2 0)))) | |
} | |
Solve [f left right] | |
(let [mid (/ (+ left right) 2.0) | |
dx 0.0001] | |
;(println left mid right '| (map f [left mid right])) | |
(if (= 0 (apply f [mid])) | |
mid | |
;(println 'x= mid) | |
(do | |
(if (>= (- right left) dx) | |
(if (> (* (f mid) (f right)) 0) | |
(Solve f left mid) | |
(Solve f mid right)) | |
;(println 'x= (float left) '| (float right)) | |
mid))))) | |
;(print (Solve f1 -2 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment