Calculate pi with an infinite series

/* I cannot successfully test while (finalResult <= 3.14) inside the while loop.
My code only allows me to enter random values of i to calculate 3.14159.

Problem statement is below:

Calculate pi from the infinite series:

pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 +... )

Print a table that shows the value of pi approximated by one term of this seris, by two terms, by three terms, etc.
How many terms of the series do you have to use before you first get
3.14, 3.141, 3.1415, and then 3.14159?

-- Thank you for your advise and assistance!
*/

#import <stdio.h>


int main (int argc, const char * argv[]) {
// insert code here...
int count = 1, i = 1, cntTester = 0;
float frac, temp;
float sumResult = 0.0, finalResult = 0.0;
while (i < 225000)
{

frac = i;
if(count%2 == 0)
{
temp = -1/frac;
}
else
{
temp = 1/frac;
}
sumResult += temp;
finalResult = 4*sumResult;
i += 2;
count++;
cntTester++;
}
printf(" Result = %.6f", finalResult);
printf(" While loop executed %d times", cntTester);

return 0;
}

MacBook Pro, Mac OS X (10.5.6)

Posted on Jul 30, 2010 8:14 PM

Reply
2 replies

Jul 31, 2010 10:59 AM in response to T2TU

Here's one approach:

#include <stdio.h>
#include <math.h>
#define PI 3.14159000
#define SHIFTiT 10000000
int main(void) {
int count = 1, i = 1, cntTester = 0;
float frac, temp;
double sumResult = 0.0;
double finalResult = 0.0;


while (lround(finalResult*SHIFTiT) != PI*SHIFTiT)
{

frac = i;

if(count%2 == 0)
{
temp = -1/frac;
}
else
{
temp = 1/frac;
}

sumResult += temp;
finalResult = 4*sumResult;
i += 2;
count++;
cntTester++;
}
printf(" Result = %.6f", finalResult);
printf(" While loop executed %d times ", cntTester);

return 0;

}

Output:

Result = 3.141590
While loop executed 377978 times
Program exited with status value:0.


Message was edited by: xnav

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Calculate pi with an infinite series

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.