/******************************************************
 * MT285 TMA02 q41.cpp
 * Pi calculator with higher precision
 *
 * programming by Allen Lam (99043953)
 * Dec 2000
 * Find approximate value of Pi by Euler's algorithm
 ******************************************************/

#include <stdio.h>
#include <math.h>
#include <time.h>
char *Filename = "pi_q41.txt"; /* filename of save file */
FILE *ptr;                     /* file pointer */

/* Using Euler's algorithm to calculate an approximate value of pi *
 * pi = sqrt(8*(1/1 + 1/3^2 + 1/5^2 + 1/7^2 +...    ))             *
 * input n determines how many terms will be added                 *
 * output the approximate pi value                                 */

long double evaluatePI(unsigned long n){
  long double denom;    /* denominator */
  long double sum;      /* sum of all terms */
  long double term;     /* value of each term */

  sum = 0.0;
  denom = 1.0;

  for (unsigned long i=0; i<n; i++){
    term = (long double)1.0/denom;
    term *= term;
    sum += term;
    denom += 2.0;
    /* if denom overflows then stop adding */
    if (denom<0.0){
      printf("Overflow occured at term %u\n", i);
      break;
    }
  }
  return sqrtl(sum*8.0);
}

/* main function that accept inputs of integer, then display Pi  */
/* Engages in endless loop until user enters zero                */

int main(){
  unsigned long n;  /* store user's input */
  long double pi;   /* store pi output */
  clock_t T1, T2;   /* start-time and stop-time */

  while (1){
    printf("Enter the number of terms (0 to quit): ");
    fflush(stdin);
    scanf("%u", &n);
    printf("Evaluating %u terms...\n", n);
    if (n==0){
      printf("Results are saved in %s\n", Filename);
      return 0;
    }

    T1 = clock();
    pi = evaluatePI(n);
    T2 = clock();

    printf("pi = %.20Lf\n", pi); /* print upto 20 decimal places */
    printf("Time Used: %.3lf seconds\n\n", double(T2 - T1)/CLOCKS_PER_SEC);

    /* also save results in file for easy reference */
    ptr = fopen(Filename, "a");
    fprintf(ptr, "pi = %.20Lf, evaluate %u terms\n", pi, n);
    fprintf(ptr, "Time Used: %.3lf seconds\n", double(T2 - T1)/CLOCKS_PER_SEC);
    fclose(ptr);
  }
}


back