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?


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;

A method to consider is using ndigits to create an 'epsilon' value.
Let's assume ndigits is 3. That give an epsilon of 0.0001

if the difference between your value from the previous iteration, and the current iteration is less than 0.0001, then you can assume you have the value you are after, and terminate the while loop.

A warning though. Doubles and long doubles have an upper limit on the number of digits they can hold accurately.

链接地址: http://www.djcxy.com/p/12242.html

上一篇: 寻找Laurent系列使用Python的函数

下一篇: Pi平方n位C ++