Pregunta

For one of my programs in my Computer Science class I have to calculate the value of pi using the following formula, I'm having trouble with the math equation in java.

Here's the math formula: Formula for 1/pi

the formulas I used were:

for (int i = 0; i < k; i++) 
{
   term = ((calculate(4*i)*(1103+(26390*i)))/(Math.pow(calculate(i), 4))*Math.pow(396, (4*i)));
   sum += term;
}
sum *= ((2*Math.sqrt(2))/9801);
sum = Math.pow(sum, -1);

The for loop should calculate the sigma sign and everything to the right of it. The next part should multiply that number by 2 square roots of 2 divided by 9801 and the final part should take that number to the -1st power, since the equation finds 1/pi this should reciprocate the fraction.

the calculate method just finds the factorial of a number.

When I run the program, the final answer is exactly pi at 1, 2.1355575437204093E-13 at 2, and it keeps printing wrong numbers. Any idea why this could be giving the wrong answer?

Thanks, any help is appreciated!

¿Fue útil?

Solución

you had your brackets wrong for your denominator:

term = (double)(calculate(4*i)*(1103+(26390*i)))/((Math.pow(calculate(i), 4))*Math.pow(396, (4*i)));

Try using doubles for your calculations. And with a value of k = 30, the result is 3.141592653589793

And determining the value of PI is like applying stochastics to find a deterministic value, using large iterations gives a better precision

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top