Created
November 20, 2013 21:01
-
-
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.
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
(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