/**
* Created by bruce on 19/5/15 -- 20:53
* 蒙特卡罗 - 蒙特卡洛方法 计算π
*/
public class MonteCarlo {
private static double MonteCarloPI(double n) {
double PI;
double x, y;
int i, sum = 0;
for (i = 0; i < n; i++) {
x = Math.random();
y = Math.random();
if ((x * x + y * y) <= 1) {
sum++;
}
}
PI = 4.0 * sum / n;
return PI;
}
public static void main(String[] args) {
System.out.println("PI:" + MonteCarlo.MonteCarloPI(1000000));
}
}
复制代码
转载于:https://juejin.im/post/5cdc0cece51d453b222b799b