我正在制作一个程序来证明计算 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);
}
}