本文为博主原创文章,转载请注明出处。
public class T {
// 循环次数
private static int LOOP = 100000;
// 圆的半径
private static double R = 0.5;
// 半径的平方
private static double R2 = Math.pow(R, 2);
// 判断是否在园内
private static boolean isInner(double x, double y) {
return R2 >= Math.pow(R - x, 2) + Math.pow(R - y, 2);
}
public static void main(String[] args) {
// 是否在圆类计数
int flag = 0;
for (int i = 0; i < LOOP; i++) {
double x = Math.random();
double y = Math.random();
if (isInner(x, y)) {
flag++;
}
}
System.out.println("Pi = " + (double) flag / LOOP * 4);
}
}