Question

Over the past couple of days, I've been trying to find a good way to generate random numbers in PHP, based on a seed. Like I'm sure most of you already know, the php rand() method is way too random for some cases, and I really need a PRNG that lets me generate the same sequence numbers over and over again based on a seed.

I've already attempted using the XORShift PRNG, the problem comes as different operating systems seem to generate different answers beause of how PHP handles Bit-shifting.

I would need some sort of algorithm that works well with PHP, that is able to generate quite large numbers, as I'll put a zero in front of it anyway and turn it into a small double. (0.RAND)

Was it helpful?

Solution

mt_srand(42);

echo mt_rand(1, 100);
echo mt_rand(1, 100);
echo mt_rand(1, 100);

This produces the sequence 64, 80, 96 on my system. It will do so every time you execute this code. You seed the generator once with your specific number (here 42), then call the generator again and again to produce a random number.


A random number generator (truly unpredictable randomness) cannot be seeded and produces a truly unpredictable random number. Computers typically cannot do this, since randomness is precisely what they do not do. Computers are deterministic and cannot produce true randomness. You need to do something like measuring radioactive decay to produce true randomness.

Pseudo random number generators appear on the face of it to behave randomly, but they are not. They start with one number, then apply deterministic mathematical operations to that number to change it and produce a different number. Each time you call the generator, it will produce a new number based on its last number. The sequence of a PRNG is therefore always the same. Good PRNGs apply operations in such a fashion that the sequence looks very randomly distributed. Typically they're seeded with something like the time of day, so they appear random if you don't seed them explicitly. If you seed them with a specific value though, they'll produce a fixed predetermined sequence of numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top