我有一個旨在模擬一些概率問題的程序(如果你感興趣的話,monty大廳問題的變體)。預期的結果不是用java實現的,而是用c#
代碼預計經過足夠的迭代後會產生50%,但在java中它總是達到60%(即使經過1000000次迭代),而在C#中出現預期的50%是否有一些不同我不知道關於Java的隨機可能?
下面是代碼:
import java.util.Random;
public class main {
public static void main(String args[]) {
Random random = new Random();
int gamesPlayed = 0;
int gamesWon = 0;
for (long i = 0; i < 1000l; i++) {
int originalPick = random.nextInt(3);
switch (originalPick) {
case (0): {
// Prize is behind door 1 (0)
// switching will always be available and will always loose
gamesPlayed++;
}
case (1):
case (2): {
int hostPick = random.nextInt(2);
if (hostPick == 0) {
// the host picked the prize and the game is not played
} else {
// The host picked the goat we switch and we win
gamesWon++;
gamesPlayed++;
}
}
}
}
System.out.print("you win "+ ((double)gamesWon/(double)gamesPlayed)* 100d+"% of games");//, gamesWon/gamesPlayed);
}
}
使用一個調試器,你會發現缺少一個'break;'子句。我建議你學習如何使用你的調試器。 (它通常在你的IDE中運行) – 2011-05-31 12:02:36
別擔心我知道如何使用debbuger :) – Jason 2011-05-31 12:06:59
@Jason爲什麼主機會隨機選擇?主人知道門後是什麼,所以永遠不會選擇獎品。 – dogbane 2011-05-31 12:07:26