【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 }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM