My birthday paradox event simulator in javascript is not working well

317 views Asked by At

I tried to do a in Javascript a birthday paradox event for 23 students, it should give me an average probability of 51% but it always give me number around 67%. Here the code:

var pers = [];
var D = 0;
for (var i = 0; i < 10000; i++) {
    for (var k = 0; k < 23; k++) {
        pers.push(Math.floor((Math.random()*366) + 1));
    }
    var npers = pers.slice();
    npers.sort();
    for ( var v = 0; v < npers.length; v++ ) {
        if (npers[v-1] == npers[v]) {
            D++;
        }
    }
    pers = [];
}
D = D / 100;
var DD = D.toString(); 
DD = DD + "%";
document.write(DD);

Could you,please, tell me where I committed a mistake ? Thank you very much. I'm sure that I've committed a mistake because the lowest percentage that I got was 66%, well over the 51% goal. (I've ran it several times). Thank you again for your help, it's been hours that I'm trying to figure out what I got wrong but I can't get it.

2

There are 2 answers

0
jlahd On BEST ANSWER

You count the number of all coincidences, not the number of cases where there are at least one coincidence in the room. That is, if on a given set there are, say, three people such that they share a birthday, or two pairs of people sharing birthdays, you increment D twice.

Add a break; after D++; and you'll get numbers around 50%.

By the way, your v loop underindexes npers (at v=0, you compare npers[-1] against npers[0]) - but that does not affect the result.

0
Steven Goodman On

The problem is with this for-loop

for ( var v = 0; v < npers.length; v++ ) {
    if (npers[v-1] == npers[v]) {
        D++;
    }
}

This will increment D (the number of successes) for every pair within a trial instead of just increment it once when you find a pair. You only care about the existence of a pair. Inserting a break; after D++; should solve this.