2016-07-28 73 views
-1

考慮到數學輸出與程序給出的數據輸出之間的差異,我遇到了一個問題。概率計數中的Java輸出

我想計算以1/6的概率獲得相同數字兩次的概率,應該是1 in 1/6 * 1/6 = 36。但是,我在42-43之間得到了答案。哪裏不對?

int guess = (int) (Math.random() * 6); 
int real = (int) (Math.random() * 6); 
int countTot = 0; 
int countReal = 0; 
int countGen = 0; 

while (true) { 
    if (countReal == 2) { 
     countGen++; 
     countReal = 0; 
     if (countGen == 1000000) { 
      System.out.println("Probability: 1 in " + countTot/countGen); 
      System.exit(0); 
     } 
    } 
    if (guess == real) { 
     countReal++; 
     countTot++; 
    } else { 
     countReal = 0; 
     countTot++; 
    } 
    guess = (int) (Math.random() * 6); 
    real = (int) (Math.random() * 6); 
} 

想想看,我這樣做是1000000倍(countGen),並把結果的平均值。提前致謝。

回答

3

運行下面的代碼:

int n = 1_000_000; 
int count = 0; 
Random rnd = new Random(); 

for (int i = 0; i < n; i++) { 
    int a = rnd.nextInt(6); 
    int b = rnd.nextInt(6); 
    int c = rnd.nextInt(6); 
    int d = rnd.nextInt(6); 

    if (a == b && c == d) { 
     count++; 
    } 
} 

System.out.println(count + "/" + n); 
System.out.println("Or about 1 in " + (n * 1.0/count)); 

給人

1000000分之27893
在35.8512888538343

所以 或約1,爲什麼你在42 1?

考慮一下,如果你得到2個數字相同,你增加countReal。如果第二次得到兩個相同的數字,則再次增加countReal(然後將其重置爲零)。如果您再次獲得2個數字再次,您已經中止計數您的跑步。這可能影響你的概率。


出的另一方式:

int n = 1_000_000; 
int count = 0; 
Random rnd = new Random(); 

boolean matched_last_time = false; 
for (int i = 0; i < n; i++) { 
    int a = rnd.nextInt(6); 
    int b = rnd.nextInt(6); 
    boolean match = a == b; 

    if (match && matched_last_time) { 
     count++; 
     // match = false; // Uncomment this line, & probability changes to 1 in 42 
    } 
    matched_last_time = match; 
} 

System.out.println(count + "/" + n); 
System.out.println("Or about 1 in " + (n * 1.0/count)); 
+1

而且這個算法比OP更清晰。 –

+0

感謝您的幫助,我現在明白了! – Playdowin

1

你指望它錯了。您正在比較投球次數(countTot)與成功次數雙比較。你應該得到1/72。但是你沒有得到它,因爲如果提前退出,如果第一對不匹配。

下面的代碼給出了正確的答案。這是不是真的很好,我會重新命名大部分的事情,但我想保持它類似於原來儘可能

int guess = (int) (Math.random() * 6); 
    int real = (int) (Math.random() * 6); 
    int countTot = 0; 
    int countReal = 0; 
    int countGen = 0; 

    while (true) { 
     if (countReal == 2) { 
      countGen++; 
      countReal = 0; 
      if (countGen == 1000000) { 
       System.out.println("Probability: 1 in " + (countTot/2)/countGen); 
       System.exit(0); 
      } 
     } 
     if (guess == real) { 
      countReal++; 
      countTot++; 
     } else { 
      countTot++; 
      if (countReal == 0) { 
       countTot++; 
      } 
      countReal = 0; 
     } 
     guess = (int) (Math.random() * 6); 
     real = (int) (Math.random() * 6); 
    } 
+0

感謝您的幫助,我明白了! – Playdowin

2

您計算連續匹配對數,而不允許重疊。如果你得到3個相同的隨機數序列,你應該計算2對,但你只計算一個。不允許重疊意味着一對取決於之前發生的情況。爲了能夠乘以概率,你必須保證事件是獨立的。