• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Need help with modifying my C++ program.

tboo

Diamond Member
Im having trouble trying to figure out how to modify my PI program below:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double pi= 0;
int accuracy = 2000;
for (long double i=1; i<=accuracy; i++)
{
pi += (long double) pow(-1, i+1)/(2*i-1);
}
pi *= 4;
cout.precision(15);
cout << "My best approximation of PI is: " << pi <<endl;

system("PAUSE");
return 0;
}

What I want to modify is to have have the program run its loop 2000 times & get a result & then 1999 times & get a result. I then want take the average of the two results & output that average. Any help is appreciated.

Thanks
 
Code:
#include <iostream>
#include <cmath>

using namespace std;

long double getPi(int accuracy)
{
    double pi= 0;
    for (int i=1; i<=accuracy; i++)
    {
        long double denom = (long double) 1/(2*i-1);
        (i%2 == 0) ? pi -= denom : pi+=denom;
    }
    return 4*pi;
}

int main()
{

cout.precision(15);

long double pi2000 = getPi(2000);
long double pi1999 = getPi(1999);

cout << "My best approximation of PI with 2000 iterations is: " << pi2000 <<endl;
cout << "My best approximation of PI with 1999 iterations is: " << pi1999 <<endl;
cout << "Average approximation of PI is: " << (pi2000+pi1999)/2 <<endl;

system("PAUSE");
return 0;
}
 
Actually, while the above works, I really don't like to compute 2000 iters and then 1999 from scratch after it was already computed when we did 2000. You could do something like this in main():
Code:
long double pi2000 = getPi(2000);

cout << "My best approximation of PI with 2000: " << pi2000 <<endl;
cout << "My best approximation of PI with 1999: " << pi2000 + (long double) 4/3999 <<endl;
cout << "Average approximation of PI is: " << (2*pi2000+(long double) 4/3999)/2 <<endl;
 
Actually, while the above works, I really don't like to compute 2000 iters and then 1999 from scratch after it was already computed when we did 2000. You could do something like this in main():
Code:
long double pi2000 = getPi(2000);

cout << "My best approximation of PI with 2000: " << pi2000 <<endl;
cout << "My best approximation of PI with 1999: " << pi2000 + (long double) 4/3999 <<endl;
cout << "Average approximation of PI is: " << (2*pi2000+(long double) 4/3999)/2 <<endl;

or you could just store the i'th value and the i-1'th value. that way you dont have to do the 4/3999 stuff.
 
Back
Top