Created
August 28, 2011 04:57
-
-
Save hans/1176259 to your computer and use it in GitHub Desktop.
Approximating pi with the Leibniz formula
This file contains hidden or 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
(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