【问题标题】:Finding the area underneath y = x^4 in the domain 2 ≤ x ≤ 4 by using a Monte Carlo Method使用蒙特卡洛方法找到域 2 ≤ x ≤ 4 中 y = x^4 下方的区域
【发布时间】:2016-06-13 21:01:33
【问题描述】:

在我的方法中,我将使用坐标为(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);

    }
}

【问题讨论】:

  • @RC。 4 亿可以,40 亿不行。

标签: java random montecarlo


【解决方案1】:

randomNum = min + rand.nextDouble((max - min) + 1); // 这里一直出错

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

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.
}

【讨论】:

  • 非常感谢!但是,我的回答似乎仍然非常不准确。虽然正确答案是 198.4,但我的估计大约是 302。我的逻辑中是否有任何错误需要修复?
  • @Abhinav 我看不到您在代码中调用此方法的位置。我建议你使用它。
  • 哦,是的,我之前评论过。感谢您指出了这一点。我现在用这个方法估计是198.3!再次感谢!
  • @Abhinav 问题很可能是额外的+1 仅适用于整数范围。这是必需的,因为您获得的值略小于上限,对于 double 这意味着 1e16 中的 ~ 1 错误(太小而无法注意到)但对于整数,这意味着您永远不会获得最大值。
  • 是的,现在说得通了
【解决方案2】:

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

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)

【讨论】:

  • 这是一种有趣的方法。我会尝试一下。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 2017-10-28
  • 2011-01-09
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多