Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better Random Generating PHP

Tags:

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

I have a project that is highly dependent upon choosing a random number 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.

like image 958
UnkwnTech Avatar asked Aug 08 '08 03:08

UnkwnTech


People also ask

How do I generate a random number in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

What is the difference between Rand and Mt_rand in PHP?

The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

What makes a good PRNG?

The PRNG should be very fast. The application should spend its time running the actual algorithms, not generating random numbers. PRNG output should have robust statistical qualities. Bits should appear to be independent and the output should closely follow the desired distribution.

What is Mt_rand function in PHP?

Definition and Usage. The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).


1 Answers

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.

like image 190
Christian Lescuyer Avatar answered Oct 10 '22 03:10

Christian Lescuyer