/******************************************************
 * MT285 TMA02 q4.cpp
 * for Q4 (a), (b) and (c)
 * Pi calculator
 * 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_q4.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                                 */

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

  sum = 0.0;
  denom = 1.0;

  for (long i=0; i<n; i++){
    term = (double)1.0/denom;
    term *= term;
    /* if terms become insignificant then stop adding to save time */
    if (term<=0.0000000000000000001){
      printf("No more adding from term %d\n", i+1);
      break;
    }
    sum += term;
    denom += 2.0;

    /* if denom overflows then stop adding */
    if (denom<=0.0){
      printf("Overflow occurred from term %d\n", i+1);
      break;
    }
  }
  return sqrt(sum*8.0);
}

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

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

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

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

    printf("pi = %.18f\n", pi); /* print upto 18 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 = %.18f, evaluate %d terms\n", pi, n);
    fprintf(ptr, "Time Used: %.3lf seconds\n", double(T2 - T1)/CLOCKS_PER_SEC);
    fclose(ptr);
  }
}



back