Need Help Calculating Pi and the percent error

My program keeps repeating an out put for each increment of N. I don't know what's going on. 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
#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++)
	{
		aPI=0;
		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 << N << endl;
		}
	}
	return 0;
}


You may wish to have a look at line 17...
Is this more like what you really want?

#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 << N << endl;
}
return 0;
}
here is a more refined code. But i don't know how to get a more accurate approximation of pi. I'm suppose to be using the leibniz formula to calculate it but instead of getting closer to 3.14 it is increasing by 3 each time. how would i go about fixing this?

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;
}
If error estimation is required, you would need to use a Maclaurin series expansion for arctan(x).
See this thread: http://cplusplus.com/forum/beginner/62868/

And estimate a bound on the error by estimating the remainder of the series.
http://en.wikipedia.org/wiki/Taylor's_theorem#Estimates_for_the_remainder
Topic archived. No new replies allowed.