Skip to content

Instantly share code, notes, and snippets.

@hans
Created August 28, 2011 04:57
Show Gist options
  • Save hans/1176259 to your computer and use it in GitHub Desktop.
Save hans/1176259 to your computer and use it in GitHub Desktop.
Approximating pi with the Leibniz formula
(use 'clojure.contrib.math)
(defn leibniz-pi [accuracy]
(let [target-accuracy (expt 10 accuracy)]
(loop [acc 1.0 sub 3 sign -1]
(let [attempt (* 4.0 acc)]
(if (> (abs (- attempt Math/PI)) target-accuracy)
(recur (+ acc (* sign (/ 1.0 sub))) (+ 2 sub) (- sign))
attempt)))))
; test
(println (leibniz-pi 0))
(println (leibniz-pi -1))
(println (leibniz-pi -4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment