Search code examples
c++pi

Pi squared to n digits C++


I found many similar topics but none of them gives me clear explanation.

I have to write program which calculates Pi squared to n digits using this taylor series:

π^2 = 12 ( 1/1^2 - 1/2^2 + 1/3^2 - 1/4^2 + ... )

I wrote this:

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    int n;
    cout << "How many digits?" << endl;
    cin >> n;
    long double Pi2 = 0;
    int i = 1;

    while( precision is less than n ) {
        if ((i%2) == 1) { 
            Pi2 += 1/pow(i,2); 
            i+=1;
    }
        else {
            Pi2 -= 1/pow(i,2); 
            i+=1; 
            }
    }

Pi2 *= 12;

cout << Pi2 << endl;
return 0;
}

and I have no idea what to write in while() ? When should this loop stop?


Solution

  • If You know the required precision, You can calculate the right value for the maximum value for n before You start the loop. Second thing: start with the most less number if You start adding all delta values.

    Similar to this

    int ndigits;
    cout << "How many digits?" << endl;
    cin >> ndigits;
    int n = int( pow( double(10), double(ndigits)/2 ) + 0.5 );
    long double Pi2 = 0;
    int i = 1;
    
    for( int i=n; i>0; --i ) 
    {
        if ((i%2) == 1) { 
            Pi2 += 1/pow(long double(i),2); 
        }
        else {
            Pi2 -= 1/pow(long double(i),2); 
        }
    }
    Pi2 *= 12;