Java 蒙特卡罗方法不精确

Java 蒙特卡罗方法不精确,java,math,pi,Java,Math,Pi,为了庆祝,我决定实现近似的值,但我的算法似乎不起作用 我试过用不同的参数跑步,但我总是得到大约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 inC

为了庆祝,我决定实现近似的值,但我的算法似乎不起作用

我试过用不同的参数跑步,但我总是得到大约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);
    }
}
公共类{
私有int迭代;//要测试多少个点
私有双r;//正方形的宽度/圆的半径(四分之一圆)
private int inCount=0;//圆内的点数
private int outCount=0;//圆外的点数
private Random getNum=new Random(System.currentTimeMillis());
近似EPI(整数迭代,双r){
this.iterations=迭代次数;
这个。r=r;
//getNum=新随机数(System.currentTimeMillis());
}
公共双精度近似(){
对于(int i=0;i=r){
返回false;
}否则
返回true;
}
私人双通道(双x,双y){
双s1=数学功率(x,2);
双s2=数学功率(y,2);
返回数学sqrt(s1+s2);
}
}

那么,假设半径为1,那么在本例中,您实际在做什么:

  • 用坐标
    (0,0)-(1,1)
  • 然后测试其中哪些在圆心位于
    (0,0)
  • 通过计算输入/输出计数器,可以得到圆段内有多少个点,以及圆段外有多少个点
  • inCount/(inCount+outCount)
    表示in点与总曲面之间的比率

    为总表面

    因此,您可以通过公式
    inCount/(inCount+outCount)*r²==pi*r²/4


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

    你是什么意思?Pi为2.41。2355年,一组数学家证明,先前认为的3.14是错误的。过去几个世纪你都去哪了?我想我没有收到备忘录。我不知道再次回到水面是安全的谢谢!我甚至在脑子里想“π*r^2/r^2,所以r^2抵消,我得到π”-Idk我的大脑在做什么。