Part II - Pi Calculation implementation.
Pi = 4 * (1/1 – 1/3 + 1/5 – 1/7 + 1/9 … (alternating + -) (1/n))
First, Pi should be a double to allow many decimals. Notice that the numerator is always 1 or -1. If you started the numerator at -1, then multiply each term by -1. So if started the numerator at -1 and multiplied it by -1, the first numerator will be 1, then the next the numerator will be -1, alternating + and -.
Then notice that the denominator goes from 1,3,5,7,9 etc. So this is counting by 2s starting at one. For loops are good when you know how many times it will go through the loop. So a for loop might be something like:
for (long denom=1; denom <n;
denom=denom+2)
where denom(inator) is the term that changes by 2 starting at 1
(not zero). We use a long to allow very large numbers
We are using longs, so we can have very long numbers. Likewise, PI should be a double (not a float) to have a very large decimal accuracy
Write a c++ program to calculate the approximate value of pi using this series. The program takes an input denom that determines the number of values we are going to use in this series. Then output the approximation of the value of pi. The more values in the series, the more accurate the data. Note 5 terms isn’t nearly enough to give you an accurate estimation of PI. You will try it with numbers read in from a file. to see the accuracy increase. Use a while loop to read in number of values from a file. Then inside that loop, use a for loop for the calculation.
12
123
1234
12345
123456
1234567
12345678
123456789
Code
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
long double calculatePi(long n);
int main()
{
ifstream inFile;
inFile.open("lab04in.txt");
long n;
cout<<fixed<<setprecision(10);
while(inFile>>n)
{
cout<<"For
"<<n<<" turms pi=
"<<calculatePi(n)<<endl;
}
}
long double calculatePi(long n)
{
int count=1;
long double pi=0;
for (long denom=1; denom <n; denom++)
{
if(denom==1)
{
pi =4;
}
else if(denom%2==0)
{
pi = pi - (4.0/(2.0*denom-1.0));
}
else
{
pi =
pi+(4.0/(2.0*denom-1.0));
}
count++;
}
return pi;
}
output
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.
Get Answers For Free
Most questions answered within 1 hours.