want to find pi... almost there

What needs changed? It doesn't approximate pi accurately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
	double pi = 1;
	long i;
	long n;
	
	cout << "Enter the value of n: ";
	cin >> n;
	cout << endl;
	
	for (i = 1; i < n; i++)
		{
		if (i % 2 == 0)
			pi = pi + (1.0 / (2.0 * i + 1.0));
		else 
			pi = pi - (1.0 / (2.0 * i + 1.0));
		}
	
		pi = 4 * pi;

	
	cout << endl << "pi = " << pi << endl;
	
	return 0;
}
with n = 1000 it will.
Yes, I see that if the user enters 1000, it works. Does that suggest a change to the code? I don't see the relevance.
Iterative approximation algorithms are expected to be relatively inaccurate when they are only allowed to iterate a small number of times. I don't know what kind of answer you're expecting. "Use a different algorithm"?
I know what you mean. It could be that I misunderstood the goal of this assignment (it's for school). "Use a different algorithm" is probably good advice, since understanding the problem is the first step to good programming. I suppose. Thank you.
Leibniz's formula converges slowly. Calculating π to 10 correct decimal places using direct summation of the series requires about 5,000,000,000 terms

http://en.wikipedia.org/wiki/Leibniz_formula_for_pi#Inefficiency

your code is fine. If you want n to be smaller then "Use a different algorithm", as helios said.


you can look up other algorithms here
http://en.wikipedia.org/wiki/Approximations_of_%CF%80#Development_of_efficient_formulae
or http://en.wikipedia.org/wiki/List_of_formulae_involving_%CF%80

http://upload.wikimedia.org/math/6/d/f/6df9e60b9d00e84e4c625696dfdd620d.png
used the first 21 terms to compute an approximation of pi correct to 11 decimal places as 3.14159265359

this one sounds promising
Last edited on
Topic archived. No new replies allowed.