# Java: Approximating pi - Program

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
    /** Approximates PI (3.14159...) with the Gregory series
     *  pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
     *  This program counts the number of terms needed
     *  to approximate pi to within range  3.14159..3.14160.
     *  This series converges exceedingly slowly, requiring
     *  over 100,000 terms to achieve the above result.
     * See http://mathworld.wolfram.com/PiFormulas.html for other series.
     * @author  Owner
     */
    public class PIseries {

        /** main method does computation of series.
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            double pi   = 0.0;
            int    termCount = 0;
            double sign = +1.0;
            double denominator = 1.0;

            while (pi < 3.14159 || pi > 3.14160) {
                pi = pi + sign*(4.0/denominator);
                System.out.println(termCount + " " + pi);

                //-- Update to next term values.
                termCount++;
                sign *= -1;
                denominator += 2.0;
            }
        }
    }