2016-07-08 4 views
0

以下のコードは、同じ誕生日を持つ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 

感謝。

+0

なぜdouble x [] = new double [size]で 'doubles'を使用していますか?ダブルマッチ= 0; '? –

+4

さて、「シミュレーション」が何であるかを調べてみてください。ランダムジェネレータを使用してシミュレーションを実行すると、期待値と同じ結果が得られません。十分なランダムサンプルを使用すると、結果は近くになります。あなたのケースでは、結果はすべてあなたの期待値に非常に近いです。あなたのプログラムはうまく動いているようです。 –

+0

@ScaryWombat sizeは、2つの値が –

答えて

1

コードに大きな問題が1つあります。配列xをランダムなデータで初期化していますが、完全に初期化する前に、すでに同じ値が2つあるかどうかを確認しています。その時点で、配列の終わりはまだ完全に初期化されません。

 // First fully filly the array x with values 
     for (int j = 0; j < size; j++) { 
      x[j] = random.nextInt(365); 
     } 

     // And then go checking for duplicates 
     for (int j = 0; j < size; j++) { 
      // etc. 

その後、結果は予測された出力に近くなりますが、依然としてまったく同じではありません。それはランダムな種の正確な値と関係があります。

+0

はい私は期待値を得ることができますが、数回の試行の後にのみ、種子なしで、より近い今、ありがとうございます。 –