我想在java中模拟生日悖论。出于某种原因,我的输出(概率)一直非常接近 1,例如模拟(10)-> 0,9268。在开始时,您可以看到我的模拟应该接近的概率。很长一段时间以来,我一直在寻找我的代码中的错误,所以我希望你们中的任何人都可以帮助我。我查找了生日悖论的其他代码,但似乎没有一个能够帮助我解决我奇怪的输出。ps你可以忽略//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();
}
}