Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example code for Bisection method in Clojure
; Example code for Bisection method
; https://en.wikipedia.org/wiki/Bisection_method
(defn f
"Example function to apply algorithm on"
[x]
(+ 3 x))
(defn distance
[a b]
(Math/abs (float (- a b))))
(defn get-sign
"Returns 1 or -1 depending if the number es positive or negative. If the
number is 0 or NaN returns nil"
[xraw]
(let [x (float xraw)]
(try
(int (/ x (Math/abs x)))
(catch Exception e
nil))))
(defn good-half
"Take the half of the segment where ends have different signs"
[a b f]
(let [c (/ (+ a b) 2)]
(cond
(= 0.0 c)
[c c]
(not= (get-sign (f c)) (get-sign (f a)))
(sort [c a])
(not= (get-sign (f c)) (get-sign (f b)))
(sort [c b]))))
(defn bolzano
"Apply Bolzano's algorithm to get the 0s of a function"
[init-a init-b f max-err]
(loop [[a b] [init-a init-b]]
(println "New section: " a b)
(if (< max-err (distance a b))
(recur (good-half a b f))
(/ (+ a b) 2))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment