package com.colin;
/**
*
* @author Colin Yan
*
*/
public class CalcPI {
private static boolean isHit(double x, double y) {
x %= 1.0;
y %= 1.0;
return x * x + y * y <= 1.0;
}
public static void main(String[] args) {
int hitTimes = 0;
int trialTimes = 10000000;
for (int i = 0; i < trialTimes; i++) {
double x = Math.random();
double y = Math.random();
hitTimes += isHit(x, y) ? 1 : 0;
}
System.out.println("PI=" + hitTimes * 4.0D / trialTimes);
}
}
概率算法求解圆周率π
最新推荐文章于 2022-06-05 16:24:46 发布