0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

Rand function yields uneven results

In my program, the average value of $integers[0]->occurences should be 20000.Why it's always larger than 20000, even after using srand()?

<?php 
        define('NUM_OF_INTS',49);    
        define('DRAWS',1000000);

            class number
            {
               public $occurences;
               public $value;

               function number()                     
               {
                   $occurences=0;
                   $value=0;
               }
            }

            $integers = array();

            //srand(time(0));
            //initialising loop
            for($i=0;$i<=NUM_OF_INTS;$i++)
            {    
                $integers[$i] = new number(); 
                $integers[$i]->value = $i;

            }
            for($i=0;$i<DRAWS;$i++)
            {                  
                $integers[rand(0,NUM_OF_INTS)]->occurences++;               
            }

            foreach($integers as $int)
                printf("%5d %5d  <br/>",$int->value,$int->occurences);
        ?>

Upvotes: 1

Views: 159

Answers (2)

Tucker
Tucker

Reputation: 7362

Have you tried using PHP's mt_rand as your generator? It is better at getting a even distribution than rand.

you can also generate two random numbers and concatenate them to get long ones.

e.g.

//desired length of 16
rand16digits = str_pad(mt_rand(0,99999999), 8 , "0").mt_rand(10000000,99999999);

Upvotes: 0

Neil
Neil

Reputation: 55392

You say that you're using WAMP.

PHP's rand() isn't very random on Windows (it only generates 15 bits of randomness) so it's unable to distribute its random numbers evenly enough between the 50 bins.

In particular, bin 0 will receive 656 / 32768 of the random numbers, which is about 0.0200195

Upvotes: 1

Related Questions