title: PI Approximation: Why is my declarative version slower?
body: <p>I'm approximating PI using the series:</p>
  
  <p><img src="https://i.stack.imgur.com/S77cO.gif" alt="PI Sereies"></p>
  
  <p>The function for the series then looks like this:</p>
  
  <pre><code>(defn- pi-series [k]
    (/ (if (even? (inc k)) 1 -1)
       (dec (* 2 k))))
  </code></pre>
  
  <p>And then my series generator looks like *:</p>
  
  <pre><code>(defn pi [n]
    (* 4
      (loop [k 1
             acc 0]
        (if (= k (inc n))
          acc
          (recur (inc k) 
                 (+ acc (double (pi-series k))))))))
  </code></pre>
  
  <p>Running <code>pi</code> with the value <code>999,999</code> produces the following:</p>
  
  <pre><code>(time (pi 999999))
  ;;=&gt; "Elapsed time: 497.686 msecs"
  ;;=&gt; 3.1415936535907734
  </code></pre>
  
  <p>That looks great, but I realize <code>pi</code> could be written more declarative. Here's what I ended up with:</p>
  
  <pre><code>(defn pi-fn [n]
    (* 4 (reduce + 
                 (map #(double (pi-series %)) 
                      (range 1 (inc n))))))
  </code></pre>
  
  <p>Which resulted in the following:</p>
  
  <pre><code>(time (pi-fn 999999))
  ;;=&gt; "Elapsed time: 4431.626 msecs"
  ;;=&gt; 3.1415936535907734
  </code></pre>
  
  <p>NOTE: The declarative version took around 4-seconds longer. Why?</p>
  
  <p>Why is the declarative version so much slower? How can I update the declarative version to make it as fast as the imperative version?</p>
  
  <hr>
  
  <ul>
  <li>I'm casting the result of pi-series to a double, because using clojure's ratio types performed a lot slower.</li>
  </ul>