javascript - Is PHP mt_rand really random or possibly biased?

223

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

85

Answer

Solution:

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
}

People are also looking for solutions to the problem: php - Adding multiple arrays to same key

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.