RubenGeert RubenGeert - 3 months ago 16
PHP Question

Is PHP mt_rand really random or possibly biased?

I did two basic A-B-C tests on my website with something like

if(mt_rand(0,2) == 0){
//THROW IN RE HERE
}elseif(mt_rand(0,2) == 1){
//THROW IN LR HERE
}else{
//THROW IN LB HERE
}


I was expecting the three conditions to occur equally often (33.3% of all pageviews). However, the impressions (as measured by Google Adsense) show very different distributions. Interestingly, both tests (two charts below) show similar patterns: LB occurs most, then RE and then LR.

The sample sizes are many thousands so the chance that this occurs by random chance is really zero.

Am I misunderstanding mr_rand()? Does anybody know if it's been properly tested? How else could these weird patterns show up?

enter image description here

Answer

You're running mt_rand test twice.. you have option 0, 1 and 2. if the test is 0, you throw RE. if not, (ie it's 1 or 2), you run the same test again, (again with options 0, 1 and 2). There you test for 1 and if it is, you throw LR. if not (it's 0 or 2) you throw LB. I can explain it further if you need..

    $number = mt_rand(0,2);
    switch ($number){
     case 0:
       //do re
       break;
     case 1:
       //do lr
       break;
     case 2:
       //do lb
       break;
    }

Or this might do the job as well

if(mt_rand(0,2) == 0){
//THROW IN RE HERE 
}elseif(mt_rand(0,1) == 1){ //we've stripped RE out, no longer deciding from 3 options
//THROW IN LR HERE
}else{
//THROW IN LB HERE
}