2015-05-03 25 views
1

我用來計算Pi使用Leibniz系列/公式的程序工作正常。下面是我的程序: -如何更快地使用Leibniz方法計算Pi的值?

public class PiFinder 
{ 
    public static void main() 
    { 
     double count = 99999.0; 
     double denominator = 1.0; 
     double pi = 0.0; 
     for (int x=0; x <= count; x++) 
     { 
      if (x%2==0) 
      { 
       pi = pi + (1/denominator); 
      } 
      else 
      { 
       pi = pi - (1/denominator); 
      } 
      denominator = denominator + 2; 
     } 
     pi = pi * 4; 
     System.out.println("Value of Pie: " + pi); 
    } 
} 

如果我增加count至999999999.0(9位)或9999999999.0(10位)值,JVM繼續運行。我如何減少JVM解釋的時間?

+2

你爲什麼要使用雙您的循環計數器? – Mat

回答

0

模運算速度很慢,但是如果模是二的冪且值是一個整數,它們可以用位操作代替。要從中受益,請將計數器x設爲整數類型。

+0

感謝哥們,我試着告訴你,但JVM操作系統仍然花費很多時間......沒有其他方法可以讓它更快嗎? –

0

下面的版本使用整數數據類型要快得多,這使得:

public class PiFinder { 
    public static void main(String[] args) { 
     int count = 99999999; 
     int denominator = 1; 
     double pi = 0.0; 

     for (int x = 0; x <= count; x++) { 
      // equivalant but not faster: 
      // ((x & 1) == 0) 
      if (x % 2 == 0) { 
       // note the 1.0: 
       // it converts the right-hand-side to double 
       pi += (1.0/denominator); 
      } else { 
       pi -= (1.0/denominator); 
      } 
      denominator += 2; 
     } 
     pi = pi * 4; 
     System.out.println("Value of Pie: " + pi); 
     System.out.println("ciao!"); 
    } 
} 
+0

謝謝,Axel。代碼運行良好。順便說一句,如何獲得小數點後50位數的Pi值? –

+0

要得到一個概述,你可以參考維基百科http://en.wikipedia.org/wiki/Pi#Modern_quest_for_more_digits –