title: Code Golf: Leibniz formula for Pi
body: <p>I recently posted <a href="https://stackoverflow.com/questions/406760/whats-your-most-controversial-programming-opinion#406948">one of my favourite interview whiteboard coding questions</a> in "<a href="https://stackoverflow.com/questions/406760/whats-your-most-controversial-programming-opinion">What's your more controversial programming opinion</a>", which is to write a function that computes Pi using the <a href="http://en.wikipedia.org/wiki/Leibniz_formula_for_pi" rel="nofollow noreferrer">Leibniz formula</a>. </p>
  
  <p>It can be approached in a number of different ways, and the exit condition takes a bit of thought, so I thought it might make an interesting code golf question. Shortest code wins!</p>
  
  <blockquote>
    <p>Given that Pi can be estimated using the function 4 * (1 - 1/3 + 1/5 - 1/7 + ...) with more terms giving greater accuracy, write a function that calculates Pi to within 0.00001.</p>
  </blockquote>
  
  <p><strong>Edit: 3 Jan 2008</strong></p>
  
  <p>As suggested in the comments I changed the exit condition to be within 0.00001 as that's what I really meant (an accuracy 5 decimal places is much harder due to rounding and so I wouldn't want to ask that in an interview, whereas within 0.00001 is an easier to understand and implement exit condition).</p>
  
  <p>Also, to answer the comments, I guess my intention was that the solution should compute the number of iterations, or check when it had done enough, but there's nothing to prevent you from pre-computing the number of iterations and using that number. I really asked the question out of interest to see what people would come up with.</p>