我想模擬java中的生日悖論。出於某種原因,我的輸出(概率)一直非常接近1模擬(10) - > 0,9268。在開始,你可以看到我的模擬應該接近的概率。我一直在尋找我的代碼中的一個錯誤,因此我希望你們中的任何一個能夠幫助我。我查了其他生日悖論的代碼,但他們沒有一個能夠幫助我處理奇怪的輸出。 p.s.你可以忽略// TODO,一旦我得到代碼並運行,就會解決這個問題。 謝謝先進!生日悖論
static final int DAYS_IN_YEAR = 365;
static final int NUMBER_OF_SIMULATIONS = 500;
LCG random;
HashSet<Integer> birthdaySet = new HashSet<Integer>();
BirthdayProblem2(){
birthdaySet.clear();
random = new LCG(); //random numbers between 0 and 1
}
int generateBirthday(){ //generates random birthday
return (int) Math.round(Math.random()*DAYS_IN_YEAR); //TODO use LGC
}
double iteration(int numberOfStudents){ //one iteration from the simulation
int sameBirthdays = 0;
for (int i = 0; i < numberOfStudents; i++){
int bd = generateBirthday();
if (birthdaySet.contains(bd)){
sameBirthdays++;
} else {
birthdaySet.add(bd);
}
}
return (double) sameBirthdays/numberOfStudents; //probability of two students having the same birthday
}
void simulation(int numberOfStudents){
double probabilitySum = 0;
for (int i = 0; i < NUMBER_OF_SIMULATIONS; i++){
probabilitySum += iteration(numberOfStudents);
}
System.out.printf("For n=%d -> P=%.4f \n", numberOfStudents, probabilitySum/NUMBER_OF_SIMULATIONS);
}
private void start() {
simulation(10); //should be about 0.1
simulation(20); //should be about 0.4
simulation(23); //should be about 0.5
simulation(35); //should be about 0.8
}
public static void main(String[] argv) {
new BirthdayProblem2().start();
}
}
方法'迭代()'應該返回boolean值,對於是否有學生同一天生日。返回的真值數除以呼叫數等於概率。 – Andreas