Skip to content

Instantly share code, notes, and snippets.

@ray1729
Created November 20, 2013 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ray1729/7570936 to your computer and use it in GitHub Desktop.
Save ray1729/7570936 to your computer and use it in GitHub Desktop.
Benchmarking some different implementations of sqrt. Requires <https://github.com/hugoduncan/criterium> to run the benchmarks.
(ns square-roots
(:require [criterium.core :refer [bench]]))
(defn square [x] (* x x))
(defn abs [x] (if (< 0 x) (- x) x))
(defn sqrt-repeated-average
[x lo hi tolerance]
(if (<= (- hi lo) tolerance)
lo
(let [y (/ (+ lo hi) 2)]
(if (> (square y) x)
(recur x lo y tolerance)
(recur x y hi tolerance)))))
(defn sqrt-inc
[x lo hi tolerance]
(if (> (square lo) x)
lo
(recur x (+ lo tolerance) hi tolerance)))
(defn sqrt-newton
[x g tolerance]
(let [g' (- g (/ (square g) (* 2.0 g)))]
(if (< (abs (- g g')) tolerance)
g'
(recur x g' tolerance))))
(comment
(bench #(sqrt-repeated-average (rand) 0.0 1.0 0.00000001))
(bench #(sqrt-inc (rand) 0.0 1.0 0.00000001))
(bench #(sqrt-newton (rand) 0.5 0.00000001)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment