pi的Leibniz公式-Java [英] Leibniz formula for pi - Java

查看:132
本文介绍了pi的Leibniz公式-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,Leibniz的pi公式为pi/4 = 1-1/3 + 1/5-1/7 + 1/9 ...我不知道如何在Java中使用此公式.我只需要一些有关如何将第二部分纳入其中的帮助.我知道我需要一个循环,并且需要一个除数变量,并且每次都需要加上2.感谢您的帮助.

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.

推荐答案

作为提示,这是一个优化的版本

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.");

打印

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.

该值应为3.14159265359

The value should be 3.14159265359

这篇关于pi的Leibniz公式-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆