【JAVA练习】- 给定精度求圆周率π

给定一个精度求圆周率π的近似值

给定公式:π/4=1-1/3+1/5-1/7+1/9-...

 1 public static void main(String[] args) {
 2     System.out.println("请输入π的精度(小数点后有效位数)");
 3     Scanner input = new Scanner(System.in);
 4     double i = input.nextDouble();
 5     double p = pi(i);
 6     NumberFormat nFormat = NumberFormat.getNumberInstance();    
 7     nFormat.setMaximumFractionDigits((int)i);//设置小数点后面位数    
 8     System.out.println(nFormat.format(p));
 9 }                    
10 
11 static double pi(double j) {    
12     double p = 1;
13     for(double i = 1; i < 50000000; i++) { //循环相加
14     double pCopy = p - (int)p;//最后两次的数值相减,精度位相减为0,说明精度已经达到
15     p += Math.pow(-1,i) / ( 2 * i + 1 ); //莱布尼兹级数求和
16     if( ( Math.abs( pCopy - ( p - (int)p ) ) * Math.pow(10,j) ) <= 0) break;//公式实现精度后退出循环
17     }
18     return p*4;
19 }

posted @ 2018-03-21 10:19  isco_22  阅读(1698)  评论(0编辑  收藏  举报