PHP 8.3.4 Released!

mt_rand

(PHP 4, PHP 5, PHP 7, PHP 8)

mt_rand通过梅森旋转(Mersenne Twister)随机数生成器生成随机值

说明

mt_rand(): int
mt_rand(int $min, int $max): int

很多老的 libc 的随机数发生器具有一些不确定和未知的特性而且很慢。mt_rand() 函数是旧的 rand() 的临时替代。该函数用了» 梅森旋转中已知的特性作为随机数发生器,它可以产生随机数值的平均速度比 libc 提供的 rand() 快四倍。

如果没有提供可选参数 minmaxmt_rand() 返回 0 到 mt_getrandmax() 之间的伪随机数。例如想要 5 到 15(包括 5 和 15)之间的随机数,用 mt_rand(5, 15)

警告

本函数并不会生成安全加密的值,并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机,则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例,random_int()random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API

参数

min

可选的、返回的最小值(默认:0)

max

可选的、返回的最大值(默认:mt_getrandmax()

返回值

返回 min(或者 0)到 max(或者是到 mt_getrandmax(),包含这个值)之间的随机整数,如果 max 小于 min 则返回 false

更新日志

版本 说明
7.2.0 rand() 已收到模偏差的 错误修复。这意味着使用特定种子生成的序列可能与 64 位机器上的 PHP 7.1.0 不同。
7.1.0 rand() 成为 mt_rand() 的别名。
7.1.0 mt_rand() 成为使用梅森旋转(Mersenne Twister)算法的固定、正确版本。要使用旧行为,请使用 mt_srand() 并将 MT_RAND_PHP 作为第二个参数。

示例

示例 #1 mt_rand() 例子

<?php
echo mt_rand(), "\n";
echo
mt_rand(), "\n";

echo
mt_rand(5, 15), "\n";
?>

以上示例的输出类似于:

1604716014
1478613278
6

注释

警告

min max 的范围必须在 getrandmax() 范围内。即 (max - min) <= getrandmax()。否则,rand() 可能会返回质量差的随机数。

参见

add a note

User Contributed Notes 3 notes

up
3
greald at ghvernuft dot nl
1 year ago
To see some systematic deviations from a universal distribution run:

<?php
$alfabet
= str_split('ADHKLMNPSTUWX');
$countalfabet = count($alfabet)-1;
$code = array_fill_keys($alfabet, 0);
for (
$L=0; $L<80*$countalfabet; $L++)
{
$lettr = floor(mt_rand ( 0, $countalfabet ));
$code[$alfabet[$lettr]]++;
}

foreach(
$code as $L => $Freq)
{
for(
$F=0; $F<$Freq; $F++)
{
echo
$L;
}
echo
"\n<br/>";
}
?>
up
3
Pawe Krawczyk
10 years ago
To reiterate the message about *not* using mt_rand() for anything security related, here's a new tool that has been just posted that recovers the seed value given a single mt_rand() output:

http://www.openwall.com/php_mt_seed/README
To Top