Leibniz formula for pi - Java [closed]

岁酱吖の 提交于 2019-12-12 06:58:06

问题


So, Leibniz's formula for pi is pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9... I can't figure out how to use this formula in Java. I just need some help on how to incorporate the second part into it. I know I need a loop and I need the have a divisor variable, and that it needs plus 2 each time. Thanks for any help.


回答1:


As a hint, this is an optimized version

long start = System.nanoTime();
double pi = 0;
for (int i = 1; i < 1000000000; i += 4) {
    pi += 8.0 / (i * (i + 2L));
}
long time = System.nanoTime() - start;
System.out.println(pi + " took " + time / 1000000 / 1e3 + " secs.");

prints

3.1415926445762157 took 1.217 secs.

If you change this loop to do backwards instead of forwards you get a more accurate. It is more accurate as the the larger numbers added at the end hides some of the cumulated rounding error for the smaller values.

3.141592651589793 took 1.222 secs.

The value should be 3.14159265359




回答2:


The for loop should look something like this:

double sum=0;
double sign=1.0;
for(int i =1;i<=limit;i+=2)
{
    sum+=sign/i;
    sign* =-1;
}


来源:https://stackoverflow.com/questions/19121438/leibniz-formula-for-pi-java

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