In: Computer Science
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.
Thanks for the question, here is the simple program in PI in C++
==================================================================
// Calculate the value of PI
#include<iostream>
using namespace std;
int main(){
long nTerms;
cout<<"Enter the number of values to be used: "; cin>>nTerms;
double pi=0.0;
long den=1;
for(long i=1;i<=nTerms;i++){
den = 2*i-1;
pi += (i%2==1)? 1.0/den:-1.0/den;
}
pi *=4;
cout<<"Approximate value of PI using "<<nTerms<<" terms is : "<<pi<<endl;
}
==================================================================