Code Golf: Calculating PI

Let’s celebrate Pi day in clojure!

Tweet

Exactly 140 characters to print 9 digits of $\pi$ (3.141592654)

(let[r reduce N(rest(range))t take](clojure.pprint/cl-format nil"~11f"
(r +' -2(map #(/(r *' 2(t % N))(r *'(t %(take-nth 2 N))))(t 99 N)))9))

“Sugared” version

There are two parts of a problem:

\[\pi = 2 \cdot (1 + \frac{1}{3} + \frac{1 \cdot 2}{3 \cdot 5} + \frac{1 \cdot 2 \cdot 3}{3 \cdot 5 \cdot 7} + ...)\]
(defn pi 
  "Calculate PI by arctangent algorithm"
  [& {:keys [iterations limit] 
      :or {iterations 99 limit 9}}]
  (->> (range 1 (inc iterations))
       (map #(/ (reduce *' (take % (iterate inc 1)))
                (reduce *' (take % (filter odd? (iterate inc 1))))))
       (reduce +')
       (* 2)
       (dec)
       (dec)))
(clojure.pprint/cl-format nil "~4f" 22/7) ;;=> "3.14"

Tweaks

To achieve 140 characters barrier, some functionality was relaxed

P.S. Calculating $\pi$ and some other irrationals is available in numberto

mishadoff 14 March 2015
blog comments powered by Disqus