简体   繁体   English

PHP - 伪随机数发生器?

[英]PHP - Pseudo Random Number Generator?

Over the past couple of days, I've been trying to find a good way to generate random numbers in PHP, based on a seed. 在过去的几天里,我一直在努力寻找一种基于种子在PHP中生成随机数的好方法。 Like I'm sure most of you already know, the php rand() method is way too random for some cases, and I really need a PRNG that lets me generate the same sequence numbers over and over again based on a seed. 就像我相信你们大多数人已经知道的那样,对于某些情况,php rand()方法太随机了,而且我真的需要一个PRNG,它允许我根据种子一遍又一遍地生成相同的序列号。

I've already attempted using the XORShift PRNG, the problem comes as different operating systems seem to generate different answers beause of how PHP handles Bit-shifting. 我已经尝试过使用XORShift PRNG,问题来自于不同的操作系统似乎因为PHP处理位移而产生不同的答案。

I would need some sort of algorithm that works well with PHP, that is able to generate quite large numbers, as I'll put a zero in front of it anyway and turn it into a small double. 我需要某种适用于PHP的算法,它能够生成相当大的数字,因为无论如何我会在它前面放一个零并将它变成一个小的双。 (0.RAND) (0.RAND)

mt_srand(42);

echo mt_rand(1, 100);
echo mt_rand(1, 100);
echo mt_rand(1, 100);

This produces the sequence 64, 80, 96 on my system. 这会在我的系统上产生序列64,80,96。 It will do so every time you execute this code. 每次执行此代码时都会这样做。 You seed the generator once with your specific number (here 42), then call the generator again and again to produce a random number. 您使用特定数字(此处为42)为生成器播种一次,然后再次调用生成器以生成随机数。


A random number generator (truly unpredictable randomness) cannot be seeded and produces a truly unpredictable random number. 随机数生成器 (真正不可预测的随机性)不能播种并产生真正不可预测的随机数。 Computers typically cannot do this, since randomness is precisely what they do not do. 计算机通常不能做到这一点,因为随机性是他们这样做正是。 Computers are deterministic and cannot produce true randomness. 计算机是确定性的,不能产生真正的随机性。 You need to do something like measuring radioactive decay to produce true randomness. 你需要做一些事情,比如测量放射性衰变,以产生真正的随机性。

Pseudo random number generators appear on the face of it to behave randomly, but they are not. 随机数生成器出现在它的表面上以随机行为,但它们不是。 They start with one number, then apply deterministic mathematical operations to that number to change it and produce a different number. 它们以一个数字开头,然后对该数字应用确定性数学运算来改变它并产生不同的数字。 Each time you call the generator, it will produce a new number based on its last number. 每次调用生成器时,它将根据其最后一个数字生成一个新数字。 The sequence of a PRNG is therefore always the same. 因此,PRNG的顺序始终相同。 Good PRNGs apply operations in such a fashion that the sequence looks very randomly distributed. 良好的PRNG以这样的方式应用操作,即序列看起来非常随机分布。 Typically they're seeded with something like the time of day, so they appear random if you don't seed them explicitly. 通常情况下,它们会播放类似于一天中的时间,因此如果您没有明确播种,它们会显得随机。 If you seed them with a specific value though, they'll produce a fixed predetermined sequence of numbers. 如果你用特定的值为它们播种,它们将产生一个固定的预定数字序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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