I want to simulate the birthday paradox in java. For some reason my output(probability) keeps getting very close to 1 e.g. simulation(10)->0,9268. In start you can see the probabilities my simulations should be close to. I have been looking for a mistake in my code for quite a while now so i hope any of you might be able to help me. I've looked up other codes of the birthday paradox but none of them seem able to help me with my strange output. p.s. you can ignore the //TODO, ill fix that once i get the code up and running. Thanks is advance!
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();
}
}