【发布时间】:2014-06-28 11:16:16
【问题描述】:
我只是想知道,如果您绘制 5 位数字,mt_rand() 数字有多独特? 在示例中,我尝试使用此函数获取 500 个随机数的列表,其中一些是重复的。
http://www.php.net/manual/en/function.mt-rand.php
<?php
header('Content-Type: text/plain');
$errors = array();
$uniques = array();
for($i = 0; $i < 500; ++$i)
{
$random_code = mt_rand(10000, 99999);
if(!in_array($random_code, $uniques))
{
$uniques[] = $random_code;
}
else
{
$errors[] = $random_code;
}
}
/**
* If you get any data in this array, it is not exactly unique
* Run this script for few times and you may see some repeats
*/
print_r($errors);
?>
可能需要多少位数才能确保循环中抽取的前 500 个随机数是唯一的?
【问题讨论】:
-
随机数不能保证是“唯一的”。
-
查看Birthday Problem 了解问题背后的一些数学知识。
-
随机!=唯一。如果您说出您使用这些数字的用途,您可能会得到更有用的答案。
标签: php