Computer Forums

Member Login

Remember Me? Sign Up! | Forgot Password
 
Slogan
 
Closed Thread
Old 02-21-2005, 06:07 PM   #1 (permalink)
 
Junior Techie

Join Date: Oct 2004

Posts: 63

See Plus Plus

Unhappy Stuck on Pi...

Hi everyone I am trying to write a program that calculates pi.
So far my program looks like this:

#include <iostream>
#include <cmath>
using namespace std;

int main ()

{

long double pi = 2.0;
int i = 1;

for (int n = 2; fabs(pi - 3.1416) > 0.0001; n+=2)
{
pi *= (n/(n-1.)) * (n/(n+1.));
i++;
cout << "i = " << i << "\tpi = " << pi << endl;
}

return 0;
}


Here's the catch - my professor only wants us to be as precise as 3.1416 - How the heck would I do that - I have tried everything and I am out of ideas???? He told us it would take between 600 and 700 iterations - I was going into the millions so I am doing something wrong...any ideas? Please help...I hate Pi.
__________________
I hate Pi
See Plus Plus is offline  
Old 02-21-2005, 09:30 PM   #2 (permalink)
 
Super Techie

Join Date: Jan 2005

Posts: 295

gab00n

Default

You can use iomanip,

cout<<fixed<<showpoint<<setprecision(4);

That way it will output the number to 4 sig figs.
__________________
\"Today\'s scientists have substituted mathematics for experiments, and they wander off through equation after equation, and eventually build a structure which has no relation to reality.\" Nikola Tesla
gab00n is offline  
Old 02-22-2005, 12:05 AM   #3 (permalink)
 
Junior Techie

Join Date: Oct 2004

Posts: 63

See Plus Plus

Default

Thanks for the reply, I actually did try that but it still goes up to maybe in the 900,000's because it is just the display on the screen that gets changed. Nonetheless, I did find something that sort of seems to work:

pi = (static_cast <double> (pi * 10000) + .0005) / 10000;

it seems to work, and keeps the iterations down to 400. I am just not sure how it works, and why the .0005 is needed so if anyone knows the answer and cares to explain, i am all ears.
__________________
I hate Pi
See Plus Plus is offline  
 
Closed Thread

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On