Skip to content

Instantly share code, notes, and snippets.

@clementi
Last active March 3, 2021 22:47
Show Gist options
  • Save clementi/123cce5bf6958e1cc0d2d70b99072df3 to your computer and use it in GitHub Desktop.
Save clementi/123cce5bf6958e1cc0d2d70b99072df3 to your computer and use it in GitHub Desktop.
Calculate pi by using the formula pi/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
#include <stdio.h>
#include <stdlib.h>
double calc_pi(int terms) {
double sum = 0;
for (int n = 0; n <= 2 * terms; n++) {
double term = 1.0 / (2 * n + 1);
if (n % 2 == 0) {
sum += term;
}
else {
sum -= term;
}
}
return 4 * sum;
}
int main(const int argc, const char** argv) {
int terms = 1000;
if (argc > 1) {
terms = atoi(argv[1]);
}
printf("%lf\n", calc_pi(terms));
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment