Created
November 23, 2021 06:28
-
-
Save cmd05/c26d5e6bfaac30cc3814fdccd2bb9cc8 to your computer and use it in GitHub Desktop.
Estimate PI using Leibiniz series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
Author
cmd05
commented
Nov 23, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment