I need to compute a pi approximation with the MadhavaLeibniz series. http://en.wikipedia.org/wiki/Leibniz it takes in user input and iterates the series that many times for precision. I need to output it as a double to 15 digets but the only thing I get out is 4 every time. I know the issue is in the mySum function because when I debug it, sum never changes after the first iteration.
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include <iomanip> // To access cout formatting settings
using std::setprecision;
// Function prototypes, used to make the main function "clean"
double mySum(int user_input);
int myProduct(int k);
int myPrompt(void);
void myPrint(double result);
int main()
{
int user_input;
double result;
do
{
user_input = myPrompt();
}while (user_input < 0);
result = mySum(user_input);
myPrint(result);
return 0;
}
int myPrompt(void)
{
int user_input;
cout << "Enter a non-negative integer: ";
cin >> user_input;
return user_input;
}
double mySum(int user_input)
{
double sum = 0;
int k;
for(int k = 0; k <= user_input; k++)
{
sum = sum + (4 * (((myProduct(k))/((2 * k) + 1))));
}
return sum;
}
int myProduct(int k)
{
if (k % 2 == 0)
{
return 1;
}
else
{
return -1;
}
}
void myPrint(double result)
{
cout << "Approximation of pi is "<< setprecision(15) << result << endl;
}
Presumably, the user_input is supposed to a positive number. But look at your do... while loop: what is that loop condition doing? When will that loop ever execute more than once?
Why is that always going to be 1? For example when the user inputs 1...the first loop will be
sum = sum + (4 * ((1)/(2*0+1))
sum = sum + (4 * 1)
but the second iteration would be
sum = sum + (4 * ((-1)/(2*1+1))
sum = sum + (4 * (-1/3))
sum = sum - 4/3
and since the previous sum was 4...it should be equal to the result of 4 - 4/3. Why isn't it that?
setprecision(15) tells the computer to output the value to 15 significant figures. But, if there are trailing zeros, they will be suppressed.
Once you get the calculation working correctly, you should see more digits. However, you could additionally use cout << std::fixed which changes the behaviour, so that instead it will always print 15 digits (in this case) after the decimal point, regardless of how many digits appear in front of the decimal point, and even when there are trailing zeros.
One other comment. There are too many parentheses. These don't do any harm, but sure make the code hard to read. You could cut it down to (something like) this: sum = sum + 4 * myProduct(k) / (2 * k + 1);
(Of course that still includes the original error, but we already discussed that.)