问题
I am developing an application in PHP and C but the result of rand is different between the two languages, even though I am using the same seed:
PHP:
srand(1);
$random = rand(); // returns 32422
C:
srand(1);
int random = rand(); // returns 41
Why is this happening?
回答1:
There is more than one way to implement a pseudo-random number generator.
Every programming language is free to specify its own rand implementation, or even to specify nothing. For example, the C specification only says that "The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX." There's no mention of how rand should work, so the compiler writers can implement rand however they like.
Many compilers use a linear congruential generator to implement rand. Even this simple algorithm has parameters that the compiler is free to specify, and which changes the sequence of numbers given by a particular seed.
Look how Borland and glibc use different parameters. You can't even trust rand to work the same across all C programs, let alone all programs in general!
来源:https://stackoverflow.com/questions/14570268/rand-seeded-the-same-way-generates-different-results