Skip to content

Instantly share code, notes, and snippets.

@cmd05
Created November 23, 2021 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmd05/c26d5e6bfaac30cc3814fdccd2bb9cc8 to your computer and use it in GitHub Desktop.
Save cmd05/c26d5e6bfaac30cc3814fdccd2bb9cc8 to your computer and use it in GitHub Desktop.
Estimate PI using Leibiniz series
#define _USE_MATH_DEFINES
#include <math.h>
#include <iostream>
#include <iomanip>
/**
* Estimate PI using Leibiniz series
* 1 - (1/3) + (1/5) - (1/7) + (1/9) .... = (pi / 4)
*/
void calc(int terms) {
long double pi = M_PI;
long double sum = 0;
long long int denom = 1;
for(int i = 0; i < terms; i++) {
sum += pow(-1, i) * ( 1 / double(denom) );
denom += 2;
long double estimate = sum * 4;
long double diff = abs(pi - estimate);
std::cout << std::setprecision(15) << std::fixed << estimate << "\t" << diff << "\n";
}
}
int main() {
int terms = pow(10, 8); // Specify calculation upto n terms
calc(terms);
}
@cmd05
Copy link
Author

cmd05 commented Nov 23, 2021

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment