庆祝Pi Day , 我决定实现 Monte Carlo method 近似值 π ,但我的算法似乎不起作用。
我试过用不同的参数运行,但我总是得到大约 3.66
我试过调试,但我无法弄明白。
public class ApproximatePi {
private int iterations; // how many points to test
private double r; // width of the square / radius of circle (quarter circle)
private int inCount = 0; // number of points that are inside the circle
private int outCount = 0; // number of points outside of the circle
private Random getNum = new Random(System.currentTimeMillis());
ApproximatePi(int iterations, double r) {
this.iterations = iterations;
this.r = r;
// getNum = new Random(System.currentTimeMillis());
}
public double getApproximation() {
for (int i = 0; i < iterations; i++) {
double x = (r) * getNum.nextDouble();
double y = (r) * getNum.nextDouble();
if (inside(x, y)) {
inCount++;
} else
outCount++;
}
double answer = (double) inCount / (double) outCount;
return answer;
}
private boolean inside(double x, double y) {
// if the hypotenuse is greater than the radius, the point is outside the circle
if (getHypot(x, y) >= r) {
return false;
} else
return true;
}
private double getHypot(double x, double y) {
double s1 = Math.pow(x, 2);
double s2 = Math.pow(y, 2);
return Math.sqrt(s1 + s2);
}
}
最佳答案
因此,假设半径为 1,那么在这种情况下,您实际上在做什么:
- 在坐标为
(0,0) - (1,1)
的正方形内生成一组 x,y 坐标 - 然后测试它们中的哪些位于圆心为
(0,0)
的圆圈内 - 通过计算进/出计数器,您可以获得圆圈段内的点数和圈段外的点数
inCount / (inCount+outCount)
表示点与总表面之间的比率
r²
是总表面积
因此,可以通过公式inCount / (inCount+outCount) * r² == pi * r² / 4
得到大约1/4圆的面积
现在,你可以说 4 * inCount / (inCount+outCount) == pi
关于java - 蒙特卡洛方法不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173622/