在我的方法找到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);
}
}
@RC。 4亿是好的,40亿不是。 –
误读,我的坏 – 2016-03-01 13:42:29