2016-03-01 71 views
0

在我的方法找到Y = X^4下方的区域中的结构域2≤X≤4,我将使用与坐标(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); 

    } 
} 
+1

@RC。 4亿是好的,40亿不是。 –

+0

误读,我的坏 – 2016-03-01 13:42:29

回答

4

randomNum = MIN + rand.nextDouble((最大 - 最小)+ 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. 
} 
+0

非常感谢!不过,我的答案似乎仍然非常不准确。虽然正确的答案是198.4,我的估计大约是302.我的逻辑中是否有任何错误需要修正? – Abhinav

+0

@Abhinav我看不到你在代码中调用这个方法的地方。我建议你使用它。 –

+0

哦,我早些时候评论过。感谢您指出了这一点。我的估计现在是198.3的方法!再次感谢! – Abhinav

0

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

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) 
+0

这是一个有趣的方法来处理它。我会尝试一下。谢谢! – Abhinav