【发布时间】: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