3 ms·
it's obvious the PHP's rand() function is using the operating system's random number generator, because as the results from Window's are awful (the image doesn'
by scott_s 19y ago
it's obvious the PHP's rand() function is using the operating system's random number generator, because as the results from Window's are awful (the image doesn't change when re-running the script), the results from the Linux environment are far superior.
Chances are, the Windows version not changing is a feature, not a bug. Random number generators require a seed. The same seed always provides the same stream of pseudo-random numbers. This is useful if you're, say, debugging a simulation that depends on pseudo-random numbers.
I don't do Windows system programming, but I'll be there's a way to change the seed, and then change the stream of numbers. So, I find it more likely that the people who implemented php on Windows were using the generator incorrectly, if the intention was different number streams.
- ajross 19y agoThis is exactly right. The windows implementation of ANSI C89 rand() was done with a 16 bit linear congruential generator back in the win16 days, and left unchanged for compatibility reasons. It's really not an insane choice on their part. Lots of applications really do rely on PRNG repeatability, and you wouldn't want a platform upgrade to interfere with that. The real lesson is that applications with solid randomness requirements need to be relying on their own generators (there are lots to choose from) or an OS-supplied RNG (e.g. /dev/urandom) and not ANSI C, which is underspecified.
- tokipin 19y agogenerally you prime the generator with the current system time
- antirez 19y agoNo it depends on the language implementation, and in the PHP documentation you can read that at every execution the seed is automatically changed. So while in C you may need srand(time(NULL)) in order to get a different set of pseudo random numbers for every program execution in PHP you need srand(CONSTANT) in order to get always the same set. Conclusion: PHP is buggy on windows if it does not change the seed at every execution like it is stated in the specification (documentation actually that == specification for PHP).