I am trying to calculate Pi using this formula: http://functions.wolfram.com/Constants/Pi/06/01/01/0005/
And this is the code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long double n;
cin >> n;
long double first_part = 0.0, second_part = 0.0, pi = 0.0;
for(int i = 0; i <= n; i++)
{
first_part += (pow(-1, n)) / ((2 * n + 1) * pow(5, 2 * n + 1));
second_part += (pow(-1, n)) / ((2 * n + 1) * pow(239, 2 * n + 1));
}
pi = (first_part * 16) - (second_part * 4);
cout << pi << endl;
return 0;
}
But something goes wrong. For example, for n = 300 it outputs 6.65027e-420. I really cannot find my mistake. Please help me. Thank you very much.
Change your code replacing all
n
toi
in thefor loop
:I ran the above code and found outout:
Careful:
pow(239, 2 * n + 1))
can overflowsecond_part
! Becausedouble
has the range:Reference here.