문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top