使用 Monte Carlo 方法在域 2 ≤ x ≤ 4 中查找 y = x^4 下面的区域

Finding the area underneath y = x^4 in the domain 2 ≤ x ≤ 4 by using a Monte Carlo Method

在我的方法中,我将使用坐标为 (2,0)(4,0)(2, 256)(4, 256) 的假想矩形。我将在这个矩形内生成随机的 xy 坐标,并找出落在由 y ≤ x^4 定义的区域内的坐标数与落在整个矩形内的坐标数之间的比率。将其乘以矩形的面积应该得到图形下方的面积。

我正在努力在定义的矩形中生成随机十进制 xy 坐标。任何帮助将不胜感激:)

我才刚刚开始融入学校,所以目前我在这方面的知识还很有限。

这是我的代码:

public class IntegralOfX2 {

    public static double randDouble(double min, double max) {
        min = 2;
        max = 4;
        Random rand = new Random();
           double randomNum;
        randomNum = min + rand.nextDouble((max - min) + 1); // an error keeps occuring here

        return randomNum;
    }



    public static void main(String[] args) {

        double x = 0; // x co-ordinate of dart
        double y = 0; // y co-ordinate of dart
        int total_darts = 0; // the total number of darts
        int success_darts = 0; // the number of successful darts
        double xmax = 4;
        double xmin = 2;
        double ymax = 256;
        double ymin = 0;
        double area = 0;


        for (int i = 0; i < 400000000; i++) {
         //   x = randDouble(xmin, xmax);
         //   y = randDouble(ymin, ymax);


          x = xmin + (Math.random() * ((xmax - xmin) + 1));
          y = ymin + (Math.random() * ((ymax - ymin) + 1));

                    total_darts++;


            if (y <= (x * x * x * x)) {
                success_darts++;
            }

        }


       double ratio = (double)success_darts/(double)total_darts;
       area = ratio * 512;
       System.out.println(area);

    }
}

randomNum = min + rand.nextDouble((max - min) + 1); // an error keeps occuring here

这是一个错误,因为不存在这样的方法。你可能想要的是

public static double randDouble(double min, double max) {
    return min + Math.random() * (max - min + Math.ulp(max));
}

您可以删除 Math.ulp,但它最接近随机整数加 1。

对于大量样本,您可以使用均匀分布,例如

int samples = 100000;
double spacing = (max - min) / spacing;
for (int i = 0; i < samples; i++) {
    double x = min + (i + 0.5) * spacing;
    // use x as an input.
}

由于您是在有限的时间间隔内执行此操作,因此通常可以通过对函数的平均高度进行 Monte Carlo 采样来获得较低的面积方差估计值。平均高度乘以底边就是面积。在伪代码中:

def f(x) {
    return x**4
}

range_min = 2
range_max = 4
range = range_max - range_min
sample_size = 100000
sum = 0
loop sample_size times {
    sum += f(range_min + range * U) // where U is a Uniform(0,1) random number
}
estimated_area = range * (sum / sample_size)