1
C - C++ / [C++] Pi Approximation using Leibniz formula
« on: February 10, 2013, 10:31:54 pm »
Made this for an assignment in Uni. Uses the Leibniz formula, which can be found at:
http://en.wikipedia.org/wiki/Leibniz_formula_for_pi
There is very little error checking involved besides making sure that the user enters a non-negative number, as it was unnecessary for the assignment. Thought I'd share anyway.
http://en.wikipedia.org/wiki/Leibniz_formula_for_pi
There is very little error checking involved besides making sure that the user enters a non-negative number, as it was unnecessary for the assignment. Thought I'd share anyway.
Code: [Select]
/*
* @author sathe
* 10 Feb 2013
*
* Computes pi using the Leibniz formula found at
* http://en.wikipedia.org/wiki/Leibniz_formula_for_pi
*
*/
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
double myPrompt(void);
double compute(double);
int main()
{
cout << "Computing Pi Series Summation by ML Formula" << endl;
cout << "===========================================" << endl;
double kLimit = myPrompt();
double approx = compute(kLimit);
cout << "Approximation of pi is " << fixed << setprecision(15) << approx << endl;
return 0;
}
double myPrompt(void)
{
double kLimit = 0;
do
{
cout << "Enter a maximum value of k in truncated series (non-negative): ";
cin >> kLimit;
}while(kLimit < 0);
return kLimit;
}
double compute(double kLimit)
{
double approx = 0;
for(double i = 0; i <= kLimit; i++)
{
approx += 4 * (pow(-1, i)/((2 * i) + 1));
}
return approx;
}