Better Random Generating PHP *

Question

I know that just using rand() is predictable, if you know what your doing, and have access to the server.

I have a project that is HIGHLY dependent on choosing a random that is as unpredictable as possible. So I'm looking for suggestions, either other built in functions, or user functions that can generate a 'better' random number.

I used this to do a little test:

$i=0;
    while($i<10000)
     {
     	$rand = rand(0,100);
    	if(!isset($array[$rand]))
    	 {
    		$array[$rand] = 1;
    	 }
    	else 
    	 {
    		$array[$rand]++;
    	 }
    	sort($array);
    	$i++;
     }

I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated.

Answer

Adding, multiplying, or truncating a poor random source will give you a poor random result. See Introduction to Randomness and Random Numbers for an explanation.

You're right about PHP rand() function. See the second figure on Statistical Analysis for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()).

One solution is to use a true random generator such as random.org. Another, if you're on Linux/BSD/etc. is to use /dev/random. If the randomness is mission critical, you will have to use a hardware random generator.

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/5611/" >Better Random Generating PHP< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment