問題描述
有誰知道 PHP 的 shuffle()
函數的隨機性是什么?它取決于操作系統嗎?它是否使用 PHP 自己的播種機?
Does anyone know what's the randomness of PHP's shuffle()
function? Does it depend on the operating system?
Does it use PHP's own seeder?
是否可以使用 mt_rand()
作為生成器?
Is it possible to use mt_rand()
as generator?
推薦答案
shuffle()
函數基于與 rand()
相同的生成器,也就是系統基于線性同余算法的生成器.這是一個快速生成器,但或多或??少具有隨機性.自 PHP 4.2.0 起,隨機生成器會自動播種,但您可以根據需要使用 srand()
函數來播種.
shuffle()
function is based on the same generator as rand()
, which is the system generator based on linear congruential algorithm. This is a fast generator, but with more or less randomness. Since PHP 4.2.0, the random generator is seeded automatically, but you can use srand()
function to seed it if you want.
mtrand()
基于 Mersenne Twister 算法,其中是最好的偽隨機算法之一.要使用該生成器對數組進行混洗,您需要編寫自己的 shuffle 函數.例如,您可以查看 Fisher-Yates 算法.編寫自己的 shuffle 函數會產生更好的隨機性,但會比內置的 shuffle 函數慢.
mtrand()
is based on Mersenne Twister algorithm, which is one of the best pseudo-random algorithms available. To shuffle an array using that generator, you'd need to write you own shuffle function. You can look for example at Fisher-Yates algorithm. Writing you own shuffle function will yield to better randomness, but will be slower than the builtin shuffle function.
這篇關于PHP 的 shuffle 函數有多隨機?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!