/*
 * app_pi.c
 * This program approximates the value of pi.
 */

#include <stdio.h>

int main ()
{
  double   epsilon;         /* The approximation error bound. */
  double   numer;           /* The numerator of the current element. */
  double   denom;           /* The denominator of the current element. */
  double   sum;             /* The sum of all elements so far. */
  int      n_elements;      /* Number of elements summed so far.

  /* Read the approximation error bound. */
  printf ("Please enter the approximation error bound: ");
  scanf ("%lf", &epsilon);

  /* Use the following formula:
   *
   *           /       1     1   2     1   2   3     1   2   3   4         \ .
   * pi = 2 * (  1  +  -  +  - * -  +  - * - * -  +  - * - * - * -  +  ...  ) 
   *           \       3     3   5     3   5   7     3   5   7   9         / .
   *
   * We sum, however, only a finite number of elements.
   * First take care of the 0'th element, which is 1 is this case.
   */
  numer = 1;
  denom = 1;
  sum = 1;
  n_elements = 1;

  /* Now take care of all the other elements ... */
  do
  {
    /* The i'th element equals the (i-1)'st element, multiplied by i and
     * divided by (2*i + 1). Thus we have: */
    numer *= n_elements;
    denom *= (2*n_elements + 1);

    /* Update the sum and the number of summed elements. */
    sum += numer / denom;
    n_elements++;

    /* Continue the summation as long as the current element is greater than
     * the error bound epsilon. */
  } while (numer / denom >= epsilon);

  /* Print the approximation result, which is twice the value of the
   * computed sum. */
  printf ("pi ~= %.10f\n", 2*sum);
  printf ("%d elements were computed and summed.\n", n_elements);

  return (0);
}

