Skip to content

Instantly share code, notes, and snippets.

@michalmarczyk
Created March 16, 2010 07:23
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 michalmarczyk/333724 to your computer and use it in GitHub Desktop.
Save michalmarczyk/333724 to your computer and use it in GitHub Desktop.
Calculate π through Euler-van Wijngaarden transformation of Gregory-Leibniz series
(use '[clojure.contrib.seq :only (reductions)])
;;; Calculate π through Euler-van Wijngaarden transformation of Gregory-Leibniz series
(def *use-exact-numbers* true)
(defn gregory-leibniz-series []
(map #(/ 4 %)
(interleave (iterate #(+ % 4) (if *use-exact-numbers* 1 1.))
(iterate #(- % 4) (if *use-exact-numbers* -3 -3.)))))
(defn partial-sums [s]
(reductions + s))
(defn average-damp [s]
(map #(/ (+ %1 %2) 2) s (rest s)))
(defn euler-transform [s]
(iterate average-damp (partial-sums s)))
(defn van-wijngaarden-pi [n]
(let [j (Math/floor (* 2/3 n))
i (- n j)]
(nth (nth (euler-transform (gregory-leibniz-series)) j) i)))
; (double (van-wijngaarden-pi 100)) ; => 3.141592653589793
; (binding [*use-exact-numbers* false] (van-wijngaarden-pi 100)) ; => 3.141592653589793
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment