Skip to content

Instantly share code, notes, and snippets.

@mikeananev
Last active March 1, 2020 05:20
Show Gist options
  • Select an option

  • Save mikeananev/9f1fba89db0f613afa9d1d309e16aa8c to your computer and use it in GitHub Desktop.

Select an option

Save mikeananev/9f1fba89db0f613afa9d1d309e16aa8c to your computer and use it in GitHub Desktop.
Calculate first N digits of PI using Clojure
(require '[clojure.core.reducers :as r])
(defn pi
"calculate accurately first k digits of PI"
[k]
(with-precision (+ 3 k)
(let [f-exp (fn [k] (let [power (fn [x n] (reduce * (repeat n x)))
k8 (* 8M k)
a (/ 1.0M (power 16M k))
b (/ 4.0M (inc k8))
c (/ 2.0M (+ 4M k8))
d (/ 1.0M (+ 5M k8))
e (/ 1.0M (+ 6M k8))
f (- b c d e)]
(* a f)))]
(bigdec (apply str (take (+ 2 k) (str (r/fold + (pmap f-exp (range (bigdec 0) k))))))))))
;; Etalon PI
;; 3,1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 0628620899 8628034825 3421170679 ...
(pi 90)
;; 3.1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 0628620899 8628034825M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment