圆周率π的计算(Calculating the Value of π)

调试了半天才搞定。

注意点:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值