【问题标题】:Leibnitz Method for Pi ProgramPi 程序的莱布尼茨方法
【发布时间】:2013-05-17 19:27:54
【问题描述】:

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

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

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

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

(结束循环,老师说要找到绝对差并使其为

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

    }
}

【问题讨论】:

  • 浮点除法的成本远大于浮点加/减的成本,所以我认为担心循环计数器的效率没有任何好处。如果您想优化程序,请尝试使用 Rational 数据结构(例如在 JScience 中)来替换您的浮点计算。

标签: java loops while-loop counter pi


【解决方案1】:

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

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);
    }
}

【讨论】:

  • 我正在尝试制作一个计数器,它会减去 2,但每次都会从正数翻转为负数。 (我是初学者 java 哈哈)-3、5、-7、9、-11、13、-15,.....
  • 另外,根据您的“最短”请求,此代码很短,但仍会比您的原始代码更快。为了“高效”,您需要删除除法和“%”运算符。
  • 这绝对对我有用,我刚试过。 5 毫秒和 250002 次迭代
  • 我不关心它的执行速度。我关心你能写多快的程序加上那个冒号是什么?还有问号?
  • 我用你的问题的答案修改了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 2013-10-21
  • 2020-11-20
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多