Calculating Pi Problems

I'm having trouble with this approximation of pi. Instead of it approaching 3.14 it is increasing by 3. Can anyone help?

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<cmath>
#include<fstream>
#include<iostream>
#include<cstdlib>
using namespace std;

int main ()
{
	double x = 1;
	double PI = 4*atan(x);
	double aPI = 0;
	double error;
	double neg1 = -1;

	for(int N = 0; N <= 15; N++)
	{
		for(int k = 0; k <= N; k++)
		{
			aPI = aPI + (pow(neg1,k) * (4/(2*k+1))) ;
			error = (aPI - PI) * 100/PI;
			//cout << "The value of pi through the leibniz formula is " << aPI << endl;
			//cout << "The percent error from the calculated and actual value is " << error << endl;
		}
		cout << aPI << endl;
		cout << error << endl;
		cout << N << endl << endl << endl;
		
	}
	return 0;
}
I looked at your code closer. I cleaned it up a bit, mostly got rid of a couple variables you don't really need and just used the corresponding constant where appropriate, changed it to a single for loop instead of a nested pair, and corrected the formula you had. Also, you need N to start at 1 not 0, that makes a huge difference. The error gets closer and closer to 0% this way and if you change the 15 to a big number you get a very small error.


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

int main ()
{
double PI = 4*atan(1);
double aPI = 0;
double error;

for(int N = 1; N <= 15; N++)
{
aPI += (double)pow(-1,N+1) / (2*N-1);

error = (4*aPI - PI) * 100/PI;
//cout << "The value of pi through the leibniz formula is " << 4*aPI << endl;
cout << "The percent error from the calculated and actual value is " << error << endl;
cout << N << endl;
}
return 0;
}
Topic archived. No new replies allowed.