在我的方法找到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