Computing Pi with C++

455 views Asked by At

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.

3

There are 3 answers

0
mazhar islam On BEST ANSWER

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.

0
Barry On

You're using the wrong variable:

for(int i = 0; i <= n; i++)
    ^^^^^
     iterating over 'i'

But:

    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));
                   ^^^^^^^^^^       ^^^^^               ^^^^^^^^^^^
                      all operations use 'n'
0
AudioBubble On

You reached the limit of floating point accuracy:

#include <cmath>
#include <iostream>

int main()
{
    // This will print inf (infinite)
    std::cout <<  std::pow(5.0, 600.0) << "\n"; // pow(5, 2 * n + 1))
    return 0;
}