【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