Skip to content

Instantly share code, notes, and snippets.

@wedesoft
Last active November 14, 2020 22:33
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 wedesoft/00a969ebffcd7f98c863aaee197a9032 to your computer and use it in GitHub Desktop.
Save wedesoft/00a969ebffcd7f98c863aaee197a9032 to your computer and use it in GitHub Desktop.
Calculate Pi in Clojure
; Calculate Pi in Clojure
; https://rosettacode.org/wiki/Pi
; https://en.wikipedia.org/wiki/Spigot_algorithm
(defn pi-digits [& {:keys [q r t k n l]}]
(if (< (- (+ (* 4 q) r) t) (* n t))
(cons n
(lazy-seq
(pi-digits :q (* q 10)
:r (* 10 (- r (* n t)))
:t t
:k k
:n (- (quot (* 10 (+ (* 3 q) r)) t) (* 10 n))
:l l)))
(pi-digits :q (* q k)
:r (* (+ (* 2 q) r) l)
:t (* t l)
:k (inc k)
:n (quot (+ (* q (+ (* 7 k) 2)) (* r l)) (* t l))
:l (+ l 2))))
(do
(print "3.")
(doseq [d (rest (pi-digits :q 1N :r 0N :t 1N :k 1N :n 3N :l 3N))]
(print (int d))
(flush)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment