以下のコードは、同じ誕生日を持つ2人ごとにランダムな日とmatcheを生成することになっています。これは誕生日の問題として知られています。コードは機能しますが、出力は間違っています。誕生日確率:間違った出力
public double simulate(int size, int count) {
Random random = new Random();
double x[] = new double[size];
double matches = 0;
boolean isMatch = false;
random.setSeed(count);
for (int i = 0; i < count; i++) {
for (int j = 0; j < size; j++) {
x[j] = random.nextInt(365);
for (int k = j + 1; k < size; k++) {
if (x[j] == x[k]) {
matches++;
isMatch = true;
break;
}
}
if (isMatch) {
isMatch = false;
break;
}
}
}
return (matches/count)*100;
}
、ここで期待される出力結果
simulate(number of people,number of simulation)
simulate(5, 10000) output = 2.71
simulate(7, 5000) output = 5.34
simulate(2, 10000) output = 0.27
simulate(9, 10000) output = 9.47
simulate(30, 20000) output = 70.675
simulate(15, 50000) output = 25.576
simulate(35, 50000) output = 81.434
simulate(45, 50000) output = 94.2
と、この実際のものと出力されます:あなたの時間のために
simulate(5, 10000) output = 2.54
simulate(7, 5000) output = 5.64
simulate(2, 10000) output = 0.18
simulate(9, 10000) output = 9.05
simulate(30, 20000) output = 68.98
simulate(15, 50000) output = 25.12
simulate(35, 50000) output = 79.90
simulate(45, 50000) output = 92.99
感謝。
なぜdouble x [] = new double [size]で 'doubles'を使用していますか?ダブルマッチ= 0; '? –
さて、「シミュレーション」が何であるかを調べてみてください。ランダムジェネレータを使用してシミュレーションを実行すると、期待値と同じ結果が得られません。十分なランダムサンプルを使用すると、結果は近くになります。あなたのケースでは、結果はすべてあなたの期待値に非常に近いです。あなたのプログラムはうまく動いているようです。 –
@ScaryWombat sizeは、2つの値が –