PHP生成隨機數的幾種方法

2021-08-04 09:20:29 字數 3017 閱讀 4820

function getrandstr($length)

return $randstr;

}$number=getrandstr(6);

echo $number;

function make_password( $length = 8 )

', '<', '>', '~', '`', '+', '=', ',',

'.', ';', ':', '/', '?', '|');

// 在 $chars 中隨機取 $length 個陣列元素鍵名

$keys = array_rand($chars, $length);

$password = '';

for($i = 0; $i < $length; $i++)

return $password;

}

function get_password( $length = 8 ) 

function getrandstr()

$code = rand(10000, 99999);

lcg_value說明

float lcg_value ( void )

lcg_value() 返回範圍為 (0, 1) 的乙個偽隨機數。本函式組合了週期為 2^31 - 85 和 2^31 - 249 的兩個同餘發生器。本函式的週期等於這兩個素數的乘積。

返回:範圍為 (0, 1) 的偽隨機數。

<?php

for($i=0; $i<5; $i++)

?>

輸出:0.11516515851995

0.064684551575297

0.68275174031189

0.55730746529099

0.70215008878091

兩種生成0~1隨機小數方法進行比較

執行10萬次基於mt_rand()與mt_getrandmax()演算法的執行時間

<?php

/** * 生成0~1隨機小數

* @param int $min

* @param int $max

* @return float

*/function randfloat($min=0, $max=1)

// 獲取microtime

function get_microtime()

// 記錄開始時間

$starttime = get_microtime();

// 執行10萬次獲取隨機小數

for($i=0; $i<100000; $i++)

// 記錄結束時間

$endtime = get_microtime();

// 輸出執行時間

printf("run time %f ms\r\n", ($endtime-$starttime)*1000);

?>

輸出:run time 266.893148 ms 

執行10萬次lcg_value()的執行時間

<?php

// 獲取microtime

function get_microtime()

// 記錄開始時間

$starttime = get_microtime();

// 執行10萬次獲取隨機小數

for($i=0; $i<100000; $i++)

// 記錄結束時間

$endtime = get_microtime();

// 輸出執行時間

printf("run time %f ms\r\n", ($endtime-$starttime)*1000);

?>

輸出:run time 86.178064 ms

執行時間上比較,因為lcg_value()直接是php原生方法,而mt_rand()與mt_getrandmax()需要呼叫兩個方法,並需要進行計算,因此lcg_value()的執行時間大約快3倍。

基於mt_rand()與mt_getrandmax()演算法的隨機效果

<?php

/** * 生成0~1隨機小數

* @param int $min

* @param int $max

* @return float

*/function randfloat($min=0, $max=1)

header('content-type: image/png');

$im = imagecreatetruecolor(512, 512);

$color1 = imagecolorallocate($im, 255, 255, 255);

$color2 = imagecolorallocate($im, 0, 0, 0);

for($y=0; $y<512; $y++)else

}}imagepng($im);

imagedestroy($im);

?>

lcg_value()的隨機效果

<?php

header('content-type: image/png');

$im = imagecreatetruecolor(512, 512);

$color1 = imagecolorallocate($im, 255, 255, 255);

$color2 = imagecolorallocate($im, 0, 0, 0);

for($y=0; $y<512; $y++)else

}}imagepng($im);

imagedestroy($im);

?>

生成隨機數 生成隨機數,幾種方法

有時用來隨機排序,隨機 需要用到隨機會函式。excel的rand 可以生成乙個0 1之間的隨機數,包含0,不包含1。使用方法,直接輸入 rand 如果需要生成0 1000之間的隨機數 rand 1000 這樣會生成小數。如果只要生成整數 如果要在兩個任意數之間生成隨機數 可以使用 round ran...

php生成隨機數的幾種方法

無引數 rand 函式使用者獲取隨機數 帶引數 rand min,max min表示從xx開始取值,max表示最大只能為xx echo rand n 得到乙個不定位數的隨機數 echo rand 5,15 在5 15之間取乙個數注意 mt rand 用法跟rand 類似,但是mt rand 的執行效...

Python 生成隨機數的幾種方法

random.random 用於生成乙個指定範圍內的隨機符點數,兩個引數其中乙個是上限,乙個是下限。如果a b,則生成隨機數 print random.uniform 10,20 18.7356606526 print random.uniform 20,10 12.5798298022random...