# Java: Approximating pi

The number pi (3.14159...) can not be expressed as any simple ratio of numbers. Computing pi is traditionally done by summing an infinite series of terms. As more and more terms in the series are evaluated, the sum approaches the value of pi.

The Gregory series is perhaps the simplest, and slowest to converge.

> pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...

Look at mathworld.wolfram.com/PiFormulas.html for a discussion of this and other series for computing pi. A precomputed value for pi is available in Java as `Math.PI`.

Question: How many terms does it take before the sum is in the range 3.14159..3.14160? Write a program to evaluate this. Warning: this series converges exceedingly slowly, requiring over 100,000 terms to achieve the above result. This type of program is also subject to infinite loops in the development process. Breaking out of an infinite loop can be a pain if you're running it from an IDE. To avoid this pain, you might want to insert something like the following in your loop during the development process

       if (termCount > 500000) break;

The preceding question assumed we already know the value of pi. A more general version of the question is to continue summing until a term becomes smaller than a specified limit, eg, 0.00001, which doesn't require knowing the final value. This technique can be applied more generally.

The purpose of this problem is for practice with loops (how would you solve this with `for`, `while`, or `do...while`?), and integer vs floating-point.

Answer: Approximating pi - Program