Search code examples
phpmathrandomstatisticsprobability

PHP Random Number Generation Issue


10,000 Loops
Range 0-1
Base Average: 0.5
Base Standard Deviation: 0.288675134595
=======================================

mt_rand()
Average: 0.337839939116
Standard Deviation: 0.264176807272
---

hexdec(sha1(*GUID*))
Average: 0.37834
Standard Deviation: 0.284251515902 <--
---

mt_rand() based from a SET of defined numbers [01234567899]
Average: 0.496042248107 <--
Standard Deviation: 0.321017564651
---

Please could someone help, I cannot seem to find a way to generate RANDOM numbers which complies with a continuous uniform distribution between 0 and 1.


Solution

  • According to php-best-random-numbers the mt_rand is the best out of the box PHP method for it.

    The problem however is with your very small subset of random numbers. If you generate random between 0 and 1 you will get a very small deviation. So you could increase the numbers when generating the numbers and then devide them by the top number.

    Check this codepad for an average of 0.50015533 and a deviation of 0.29015651152368 on my run.

    Keep in mind that if you start rounding the values again to get an actual 0 or 1, your standard deviation will be around 0.5.

    The code:

    <?php
    $start = 0;
    $top = 10000;
    $ar = array();
    for ($x=1;$x<=10000;$x++) {
      $val = mt_rand($start, $top) / $top;
      $ar[] = $val;
    }
    
    $mean = array_sum($ar) / sizeof($ar);
    
    $devs = array();
    foreach($ar as $num) {
        $devs[] = pow($num - $mean, 2);
    }
    
    $standard_deviation = sqrt(array_sum($devs) / sizeof($devs));
    
    echo 'Max: ' . max($ar);
    echo chr(10);
    echo 'Min: ' . min($ar);
    echo chr(10);
    echo 'Average: ' . $mean;
    echo chr(10);
    echo 'Deviation: ' . $standard_deviation;
    ?>