我试图使用/ dev/urandom中的字节来生成随机浮点数.目前我最好的想法是让平台精确度做如下:
$maximumPrecision = strlen('' . 1/3) - 2;
Run Code Online (Sandbox Code Playgroud)
然后在$ loopPrecision告诉我们的循环次数中构造一个0-9的字符串.例如,如果精度为12,我将生成12个随机数并将它们连接起来.我认为这是一个丑陋的想法.
更新:这有意义吗?
$bytes =getRandomBytes(7); // Just a function that returns random bytes.
$bytes[6] = $bytes[6] & chr(15); // Get rid off the other half
$bytes .= chr(0); // Add a null byte
$parts = unpack('V2', $bytes);
$number = $parts[1] + pow(2.0, 32) * $parts[2];
$number /= pow(2.0, 52);
Run Code Online (Sandbox Code Playgroud)
PHP 的 float 类型通常实现为IEEE double。这种格式的尾数精度为 52 位,因此原则上它应该能够在 [0, 1) 中生成 2 52 个不同的统一数。
因此,您可以从 /dev/urandom 中提取 52 位,解释为整数,然后除以 2 52。例如:
// assume we have 52 bits of data, little endian.
$bytes = "\x12\x34\x56\x78\x9a\xbc\x0d\x00";
// ^ ^^ 12 bits of padding.
$parts = unpack('V2', $bytes);
$theNumber = $parts[1] + pow(2.0, 32) * $parts[2]; // <-- this is precise.
$theNumber /= pow(2.0, 52); // <-- this is precise.
Run Code Online (Sandbox Code Playgroud)