Hi everyone, having some real trouble with my work.
It is supposed to be a function that calculates pi to an accuracy specified by the user.
More info:
Specification:
The function called get_pi must return a double precision approximation to pi .
The accuracy of the approximation to pi is to be determined by an argument to
the function. This argument, called accuracy, a double precision value, will be the maximum % error of the approximation. For example, if accuracy = 12.2 then the returned value must be guaranteed to be in the range pi+/-12.2%.
The interface for the function:
double get_pi(double accuracy);
The Implementation:
One method of evaluating pi is to use the fact that tan(pi/4)=1
A power series for arctan(x) is given by
1/4*pi = (x^(2n+1))/(2n+1)
we should be able to write a summing loop to evaluate this series with x=1 that gives us pi/4.
However, how do we deal with the fact that the power series has an infinite number of terms? We need a termination criterion, which depends upon the accuracy demanded.
As we are not doing a maths course here, I suggest that we accept the following
compromise, an error estimate being:
+/- 4*(x^(2n+1))/(2n+1)
THANK YOU VERY MUCH FOR YOUR 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 31 32 33 34 35 36 37 38
|
#include <iostream>
using namespace std;
double get_pi (double accuracy)
{
double tolerance, series, working, estimated_error, est_pi;
int n, a;
n=0;
a=1;
tolerance = 100 - accuracy;
series = (((1^(2*n))+1)/(2*n+1));
estimated_error = 4*(((1^(2*n))+1)/(2*n+1));
est_pi = (4*working);
while (estimated_error>((tolerance/100)*working))
{
a=a*-1;
n++;
series = series*a;
working = working+(4*series);
}
return (est_pi);
}
int main()
{
double acc, out;
cout << "Please enter the percentage accuracy you wish pi to be calculated to:\n";
cin >> acc;
out = get_pi(acc);
cout << "Your value of pi is: " <<out;
return 0;
}
|