pi-c.c
/* File: pi-c.c
*
* Purpose: Estimates pi using the Madhava–Leibniz series.
*
* Compile: gcc -g -Wall -o pi-c pi-c.c
* (bonus: try with -O3 ?)
* Run: ./pi-c num-intervals
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
/* We define pi here so we can check and see how accurate our computation is. */
#define PI 3.141592653589793238462643
double get_time(void)
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + t.tv_usec / 1000000.0;
}
int main(int argc, char *argv[])
{
if (argc <= 1) {
fprintf(stderr, "Usage: %s num-intervals\n", argv[0]);
return EXIT_FAILURE;
}
unsigned long long intervals = strtoull(argv[1], NULL, 10);
printf("Intervals: %llu\n", intervals);
double time1 = get_time();
long double total = 0.0;
for (unsigned long long i = 0; i < intervals; ++i) {
if (i % 2 == 0) {
total = total + (1.0 / ((2.0 * i) + 1));
} else {
total = total - (1.0 / ((2.0 * i) + 1));
}
}
total = total * 4;
double time2 = get_time();
printf(" Result: %.20Lf\n", total);
printf(" Accuracy: %.20Lf\n", PI - total);
printf(" Time: %.10lf\n", time2 - time1);
}