Author Topic: [C++] Pi Approximation using Leibniz formula  (Read 15454 times)

0 Members and 1 Guest are viewing this topic.

Offline sathe

  • NULL
  • Posts: 3
  • Cookies: 0
    • View Profile
[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.


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;
}

Offline WirelessDesert

  • Knight
  • **
  • Posts: 356
  • Cookies: 10
  • I think...
    • View Profile
Re: [C++] Pi Approximation using Leibniz formula
« Reply #1 on: February 12, 2013, 11:22:00 am »
Kewl, thanks for sharing!
Check out my arduino project: Moving car - School project!
"I'm like current, I always take the easiest route."