rand() seeded the same way generates different results

放肆的年华 提交于 2020-01-06 08:01:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!