java - 蒙特卡洛方法不准确

标签 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,那么在这种情况下,您实际上在做什么:

  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

关于java - 蒙特卡洛方法不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173622/

相关文章:

python - 在张量分解后重新组合张量

java - 单位圆程序舍入

java - 用 BigDecimal 计算圆周率

java - 在导出的 jar 中处理导出的库 java

java - SSL 不适用于 Android 2.2(仅适用于 2.3)

Java Bean 复合注入(inject)

math - 四元数仍然有万向节锁

c# - 计算二项式系数的算法

java - Java中如何使用多线程编写圆周率计算程序?

java - 升级到 2.7 ClassNotFoundException : org. mockito.exceptions.Reporter 后运行测试