0

我正在制作一个程序来证明计算 PI 的莱布尼茨方法。

(pi/4) = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...

我对此采取了一种非常有趣的方法,我只是想知道是否有更简单的方法可以做到这一点。

我所做的是将变量j作为分母。主要想法是让计数器从-3开始,然后转到-5的绝对值,然后是-7,然后是-9的绝对值......等等。你觉得有什么办法可以让它变小吗?谢谢 :)

(为了结束循环,老师说要找到绝对差,并使其小于 1e-6)

public class Leibnitz
{
    public static void main(String argv[])
    {
        double answer = (Math.PI) / 4; //answer
        double numTheory = 1; //answer
        double j = -3; //counts the Denominator
        double piFrac; //extra variable for calc
        int i = 0; //counts loop

        System.out.print("How many iterations does it take to compute pi this series: ");

        while (Math.abs(answer - numTheory) > 1e-6)
        {
            if (j % 4 == -1) //checks if number should be negative (5,9,... needs to be positive so -5 % 4 = -1, -9 % 4 = -1)
                j = Math.abs(j);

            piFrac = (1 / j); //fraction of pie
            numTheory = numTheory + piFrac; //answer

            if (j > 0) //makes counter a negative
                j = -j;

            j -= 2; //goes down by 2

            i++; //counts how many times it goes thru the loop
        }

        System.out.println(i);

    }
}
4

1 回答 1

0

如果您只是在寻找优化。这应该有效,它更短且可读性也不会太低。

while (Math.abs(answer + numTheory) > 1e-6)
{
    j += 2;
    numTheory += 1 / (++i % 2 == 0 ? -j : j);
}

解释,代码(++i % 2 == 0 ? -j : j)被评估如下

(expression) ? (if branch) : (else branch)

所以用英语。 if (++i mod 2 equals 0) then do (-j) else do (j)

完整代码:

public class Leibnitz
{
    public static void main(String argv[])
    {
        double answer = Math.PI / 4; //answer
        double numTheory = 1; //answer
        double j = -3; //counts the Denominator
        int i = 0; //counts loop

        System.out.print("How many iterations does it take to compute pi this series: ");
        while (Math.abs(answer + numTheory) > 1e-6)
        {
            j += 2;
            numTheory += 1 / (++i % 2 == 0 ? -j : j);
        }
        System.out.println(i);
    }
}
于 2013-05-17T19:37:34.023 回答