蒙特卡洛方法不准确

Tim*_*092 3 java math pi

为了庆祝Pi Day,我决定采用Monte Carlo方法近似计算的值,但是我的算法似乎无效。

我尝试使用不同的参数运行,但总能获得约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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Iły*_*sov 5

因此,假设半径为1,那么在这种情况下,您实际上正在做什么:

  1. 在具有坐标的正方形内生成一堆x,y坐标 (0,0) - (1,1)
  2. 然后,您可以测试其中哪些位于圆心内, (0,0)
  3. 通过计入/计出计数器,您可以获得圆的线段内有多少个点,外圈有多少个点

inCount / (inCount+outCount) 表示点与总表面之间的比率

是总表面

因此,您可以通过公式获得大约1/4圆的面积 inCount / (inCount+outCount) * r² == pi * r² / 4

现在,你可以说 4 * inCount / (inCount+outCount) == pi