Java-Pi的幾種實現
阿新 • • 發佈:2019-01-29
1、無窮級數計算 p = 1 - 1/3 + 1/5 -1/7+..... π=4p
2、使用 Nilakantha 級數 π = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + 4/(10*11*12) - (4/(12*13*14) .....
3、假設有一個圓半徑為1,所以四分之一圓面積就為PI,而包括此四分之一圓的正方形面積就為1,
如果隨意的在正方形中投射飛標(點)好了,則這些飛標(點)有些會落於四分之一圓內,假設所投射的飛標(點)有n點,在圓內的飛標(點)有c點,則依比例來算。
public class Main { public static void main(String[] args) { gailv(); } //無窮級數計算 1 - 1/3 + 1/5 -1/7+..... public static void wuqiongjishu() { double p1 = 1, p2 = 0; double i = 1; double flag = 1; double diff = Math.pow(0.1, 9); while (Math.abs(p1 - p2) >= diff) { i += 2; flag = -flag; p2 = p1; p1 = p1 + flag / i; } System.out.println(p1 * 4); } public static void gailv() { int N = (int)Math.pow(2,25); double a[] = new double[N]; double b[] = new double[N]; for (int i = 0; i < N; i++) { a[i] = Math.random(); b[i] = Math.random(); } int cnt = 0; for (int i=0;i<N;i++){ double c = a[i] * a[i] + b[i]*b[i]; if (c<=1){ cnt ++; } } System.out.println(4.0*cnt/N); } }