Search code examples
c++formulapi

Computing Pi with C++


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.


Solution

  • Change your code replacing all n to i in the for loop:

    #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, i)) / ((2 * i + 1) * pow(5, 2 * i + 1)); 
    
            second_part += (pow(-1, i)) / ((2 * i + 1) * pow(239, 2 * i + 1));
        }
    
        pi = (first_part * 16) - (second_part * 4);
    
        cout << pi << endl;
    
        return 0;
    }
    

    I ran the above code and found outout:

    3.14159

    Careful: pow(239, 2 * n + 1)) can overflow second_part! Because double has the range:

    1.7E +/- 308 (15 digits)
    

    Reference here.