java 计算 pi 到 6 位有效数字

java compute pi to 6 significant figurs

我在使用这个程序时遇到问题,我们应该将 pi 计算为六位有效数字,不进行四舍五入且不使用数学库常量,该程序还应该显示达到 6 sig fig 所需的迭代次数准确性以及输出中的数学常数,到目前为止,我只是想着手计算 pi,我完全不知道如何获得六个 6 无花果有或没有四舍五入,更不用说如何迭代需要多次迭代才能达到 6 个 sig figs 请帮助。

"Write an algorithm and program to compute π, using the formula described in the text PI/4 =1-(1/3)+(1/5)-(1/7)+(1/9)...." 输出将包括 π 的计算值、π 的数学库常量预期值以及达到六位有效数字精度所需的迭代次数。迭代次数可能超过 250,000 次。使您的输出清晰易读,以便比较结果。

这是我目前用来计算 pi 的代码,但即使这样我也不确定是否正确。

public static void main(String[] args) throws Exception {      
    Double pi=1.0;
    int s=1;
    for (double j=3.0; j<100.0; j=j+2)
    {
        if (s % 2 == 0)
            pi = pi + (1/j);
        else
            pi = pi - (1/j);
        s = s + 1;
    }
    System.out.println(4*pi);

考虑

        String piStr = "3.14159";
        Double pi=1.0;
        int s=1;
        double j=3.0; 
        String lcl = "";
        String upToNCharacters = "";
        while (true)
        {
            if (s % 2 == 0)
                pi = pi + (1/j);
            else
                pi = pi - (1/j);

            s = s + 1;
            j=j+2;
            
            lcl = "" + 4 * pi;
            upToNCharacters = lcl.substring(0, Math.min(lcl.length(), 7));
            if (upToNCharacters.equals(piStr)) {
                break;
            }
        }
        System.out.println(upToNCharacters);
        System.out.println("after " + s);

输出

3.14159

after 136121

理想情况下,您应该将计算封装在 class:

public class PI {
    private double estimate = 1.0;
    private int iteration = 0;

    public double getEstimate() {
        return 4 * estimate;
    }

    public void iterate() {
        double ratio = 1.0 / (iteration * 2 + 3);
        if (iteration % 2 == 0)
            estimate -= ratio;
        else
            estimate += ratio;
        iteration++;
    } 
}

然后循环变得非常简单:

PI pi = new PI();
while (Math.round(pi.getEstimate() * 1e5) != Math.round(Math.PI * 1e5))
    pi.iterate();

对我来说,这需要 130,657 次迭代

所以大概有一种方法可以使用交替级数定理对误差进行先验估计。但是假设您不知道该定理或不相信您的数学(如果您知道,只需将上面的 100.0 更改为正确的数字。上面估计的 800000.0 可以工作,只是勉强)。也许这里有一些更安全的方法,但最好只在循环中每 1000 次而不是每次检查一次估计的优度?

Double pi=1.0; Boolean closeEnough=false;
    int s=1;
    for (double j=3.0; (!closeEnough); j=j+2)
    {
        if (s % 2 == 0)
            pi = pi + (1/j);
        else
            pi = pi - (1/j);
        if (Math.abs(4/(j+2))<0.000005)
            closeEnough=true;

        s = s + 1;
    }