蒙特卡洛方法不准确

时间:2019-03-14 23:45:44

标签: java math pi

为了庆祝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 :(得分:5)

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

  1. 在具有坐标(0,0) - (1,1)的正方形内生成x,y坐标束
  2. 然后,您测试其中哪个位于中心(0,0)的圆内
  3. 通过对计数器进行计数,您可以在圆弧段内获得多少点,而在圆弧范围内得到多少点

inCount / (inCount+outCount)代表点数与总表面的比率

是总表面

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

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