简体   繁体   中英

rand() seeded the same way generates different results

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?

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.

LCG参数

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM