Approximating Pi in C++

Nov 22, 2011 at 5:49am
I am supposed to make a program that approximates pi with the following formula in C++

pi = sqrt( 6*(1 + 1/4 + 1/9 + 1/16 + 1/25 +.......) )

So far I have whats below, i think my equation used is wrong in the program and i dont know how to fix it, it compiles fine, but when run it gives a result of 1.#INF instead of 3.14..... any help would be appreciated


#include <iostream>
#include <conio.h>
#include <math.h>

using namespace std;

int main ()
{

double x=0;
long double pi;
double i;
cout << " To how many terms? ";
cin >> i;

for (long int n = 2; n <= i; n++)
{
x += 1.0/(n*n);
}
pi =sqrt(6*(1+x));
cout << " Estimated PI value to " << i << " terms: "<< pi;

getch();
}
Last edited on Nov 22, 2011 at 5:55am
Nov 22, 2011 at 6:25am
Your formula for adding the fractions is incorrect.
each succeeding denominator is increased by 5,7,9.........and so on
so your formula needs to reflect that.[s]
[/s]
Last edited on Nov 22, 2011 at 11:49pm
Nov 22, 2011 at 6:31am
change the code like this then you will get the out put in readable form.

1
2
3
4
5
double x=0.0;
long double pi;
int i;
cout << " To how many terms? ";
cin >> i;

Nov 22, 2011 at 11:50pm
Oooops disregard my thread above........your x+= expression is correct
when i ran your code i got this:
/* To how many terms? 250
Estimated PI value to 250 terms: 3.13778/*
Last edited on Nov 23, 2011 at 1:34am
Topic archived. No new replies allowed.