如何在 PHP 中获取一系列可重现的伪随机数?
在旧版本的 PHP 中,我可以通过在 RNG 中使用相同的种子来做到这一点。 , 但它不再起作用,因为 PHP 改变了 rand 和 mt_rand 的工作方式。
另请参阅 PHP.net 页面中的此评论:
Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code.
该评论的链接:http://www.php.net/manual/en/function.srand.php#102636
有没有现成的解决方案?我没有时间也没有经验来创建自己的伪随机生成器代码。
我的目标是有一个代码
<?php
//( pseudo random code here...)
$the_seed = 123; // 123 is just a number for demo purposes, NOT a static number
//...i hope you get the idea. It's just a hardcoded seed,
// it could be a seed based on a user-id, a date etc...
// we need the same output for a given seed.
//( pseudo random code here...)
// ...and finally
echo $the_random_number;
?>
所以每次我访问这个页面时,我应该得到相同的号码。
最佳答案
Mersenne Twist 是一个很好的快速 PRNG,这里有一个公共(public)领域的 PHP 实现:
http://kingfisher.nfshost.com/sw/twister/
这仅适用于 PHP 5.3.0 及更高版本。
关于php - 可重现的随机数系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8069326/