调试了半天才搞定。
注意点:
1.迭代次数=(计算公式π=4-4/3+4/5-4/7+4/9-4/11+...中的项数)-1,如,第一次迭代,公式中有两项,即π=4-4/3
2.从循环中提取计算结果首次匹配3.14159的counter时,为了保护该值hitTmes,增加了判断条件:hitTimes==0时才会修改hitTimes,否则,不能修改
看似简单的计算,实际执行起来也挺耗时的,加油!
代码如下:
//Java how to program, 10th edtion
//Exercise 5.20, Calculating the Value of π
/**(Calculating the Value of π) Calculate the value of π from the infinite series:
* π=4-4/3+4/5-4/7+4/9-4/11+...
Print a table that shows the value of π approximated by computing the first 200,000 terms of this
series. How many terms do you have to use before you first get a value that begins with 3.14159?*/
import java.util.Scanner;
public class PaiCalc {
public static void main(String[] args){
int counter=1;
double paiValue=4.0;
int hitTimes=0;
while(counter<136125){
paiValue+=Math.pow(-1,counter)*4/(2*counter+1);
System.out.printf("第%d次迭代计算\t%.14f\n",counter,paiValue);
if (hitTimes==0 && Double.toString(paiValue).substring(0, 7).equals("3.14159"))
hitTimes=counter;
counter++;
}
System.out.printf("第%d次迭代计算得到结果3.14159\n",hitTimes);
}
}
运行结果:
(前136117行省略)
第136118次迭代计算 3.14160000010273
第136119次迭代计算 3.14158530713074
第136120次迭代计算 3.14159999999479
第136121次迭代计算 3.14158530723868
第136122次迭代计算 3.14159999988685
第136123次迭代计算 3.14158530734662
第136124次迭代计算 3.14159999977891
第136120次迭代计算得到结果3.14159