Java - Ramanujan Series for pi

瘦欲@ 提交于 2020-01-06 07:03:55

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/21600878/java-ramanujan-series-for-pi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!