超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<mt_randoctdec>
Last updated: Fri, 22 Jun 2007

mt_srand

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

mt_srand -- 播下一个更好的随机数发生器种子

说明

void mt_srand ( int seed)

seed 来给随机数发生器播种。

<?php
// seed with microseconds
function make_seed() {
   list(
$usec, $sec) = explode(' ', microtime());
   return (float)
$sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?>

注: 在 PHP 4.2.0 中,无需用函数 srand()mt_srand()来搜寻随机数生成器,它将被自动完成。

参见 mt_rand()mt_getrandmax()srand()




add a note add a note User Contributed Notes
mt_srand
php_public at macfreek dot nl
07-Oct-2001 11:57
The seed is not good. The make_seed() function returns a big number (around 1.0E14), this number is bigger then 2147483647, the max. size of an integer. If the result of make_seed is first converted to an integer, which -on my setup- always becomes -2147483648. So, the above code always returns the same seed and I always end up with the same random numbers.

Note: This might be related to a bug noted on http://www.php.net/manual/en/language.types.integer.php. But I couldn't confirm this, since it will be fixed in PHP 4.0.7, but that isn't released yet at the time of writing)

I was also not able to fix it by return the seed modulo 2147483647.
So for now, I just suggest change the seed function as:

function make_seed() {
   return (double)microtime()*1000000;
}

See also: uniqid()

<mt_randoctdec>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22