產生更好的隨機數

mt_rand

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

mt_rand產生更好的隨機數

說明

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

很多老的 libc 的隨機數發生器具有一些不確定和未知的特性而且很慢。PHP 的 rand() 函式預設使用 libc 隨機數發生器。mt_rand() 函式是非正式用來替換它的。該函式用了 » Mersenne Twister 中已知的特性作為隨機數發生器,它可以產生隨機數值的平均速度比 libc 提供的 rand() 快四倍。

如果沒有提供可選參數 minmaxmt_rand() 返回 0 到 mt_getrandmax() 之間的偽隨機數。例如想要 5 到 15(包括 5 和 15)之間的隨機數,用 mt_rand(5, 15)

參數

min

可選的、返回的最小值(預設:0)

max

可選的、返回的最大值(預設:mt_getrandmax()

返回值

返回 min (或者 0) 到 max (或者是到 mt_getrandmax() ,包含這個值)之間的隨機整數。

更新日誌

版本 說明
4.2.0隨機數發生器自動進行播種。

範例

示例 #1 mt_rand() 例子

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

echo 
mt_rand(515);
?>

以上例程的輸出類似於:

1604716014
1478613278
6

註釋

警告

The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 2^32.

參見

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *