試圖回到Java並決定處理PI,從而獲得更高的PI精度。所以,我提出基於諧波系列此程序:如何使用Harmonic Series
public static void main(String [] args)
{
double denominator = 1.0;
double tempValue;
double PI = 0.0;
// End point for program
double stopPoint = 1234.5;
for(int i = 1; i < stopPoint; i++ )
{
tempValue = Math.sqrt((1/(denominator*denominator))/6);
PI = PI + tempValue;
denominator = denominator + 1.0;
}
System.out.println("PI = " + PI);
的應用程序打印此:
PI = 3.1417306496998294
所以你可以看到它的溫和運行。但是,當我再次改變停止點值時,我根本沒有得到精度的改變。
例如將其更改爲1234.75
給出了相同的答案 - 或者print
無法顯示確切值?如果是的話,打印出這些值的最佳方式是什麼?
感謝
編輯
我已經添加了這些代碼作爲其更改了代碼張貼以上。其中一些變化包括使用Big Decimal
和包含while loop
而不是for
。
import java.math.BigDecimal;
import java.math.MathContext;
public class MyPI
{
final static BigDecimal ONE = new BigDecimal(1);
final static BigDecimal SIX = new BigDecimal(6);
public static void main(String [] args)
{
BigDecimal deno, temp, tempPI;
int start, end;
start = 1;
end = 500000;
temp = new BigDecimal(0);
// Starting denominator point
deno = ONE;
while(start < end)
{
// Without precision and rounding mode, it will try to return a
// never ending number
temp = temp.add(ONE.divide(deno.pow(2),MathContext.DECIMAL64));
deno = deno.add(ONE);
start = start + 1;
}
tempPI = temp.multiply(SIX);
// Need to convert to double for square root
double PI = Math.sqrt(tempPI.doubleValue());
System.out.println("PI: " + PI);
}
}
這將產生以下結果:
PI: 3.1415907437318054
感謝所有幫助 - 可能會添加一個計時器來跟蹤它需要多長時間來做到這一點。
諧波級數收斂*很慢***到PI。 –
爲什麼不有一個長時間的停留點? – Tarik
_Very_慢,例如[(http://stackoverflow.com/a/17084000/230513))。 – trashgod