Yourat1969
Yourat1969

Reputation: 43

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.

Upvotes: 4

Views: 479

Answers (3)

mazhar islam
mazhar islam

Reputation: 5619

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.

Upvotes: 2

user2249683
user2249683

Reputation:

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;
}

Upvotes: 3

Barry
Barry

Reputation: 302852

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'

Upvotes: 8

Related Questions