ScotlandPHP

mt_srand

(PHP 4, PHP 5, PHP 7)

mt_srandInitialise une meilleure valeur aléatoire

Description

void mt_srand ([ int $seed ] )

mt_srand() initialise le générateur de valeurs aléatoires avec seed ou avec une valeur aléatoire si aucun paramètre seed n'est fourni.

Liste de paramètres

seed

Une valeur d'initialisation aléatoire

Valeurs de retour

Aucune valeur n'est retournée.

Historique

Version Description
5.2.1 L'implémentation Mersenne Twister en PHP utilise maintenant un nouvel algorithme d'initialisation, réalisé par Richard Wagner. Des initialisations identiques ne produisent plus la même séquence de valeurs, comme cela pouvait être le cas dans les versions antérieures. Ce comportement ne devrait plus changer.

Exemples

Exemple #1 Exemple avec mt_srand()

<?php
// initialisation avec des microsecondes
function make_seed()
{
  list(
$usec$sec) = explode(' 'microtime());
  return (float) 
$sec + ((float) $usec 100000);
}
mt_srand(make_seed());
$randval mt_rand();
?>

Voir aussi

  • mt_rand() - Génère une meilleure valeur aléatoire
  • mt_getrandmax() - La plus grande valeur aléatoire possible
  • srand() - Initialise le générateur de nombres aléatoires

add a note add a note

User Contributed Notes 21 notes

up
4
Alderin1 at gmail dot com
9 years ago
I think Joe was a little confused by the wording.  The note meant that implementations of mt_rand() before the change would generate a different set of pseudorandom numbers than would implementations of mt_rand() after the change for the same seed.

That's how it reads for me, anyway.
up
11
slonmron_no_spam_please_ at yahoo dot com
10 years ago
Looks like mt_rand() gives same result for different seeds when the lowest bits are different only. Try this:

#!/usr/bin/php -q
<?php

$min
= -17;
$max = $min + 48; // 48 is to fit the results in my console

for ($testseed=$min; $testseed<$max; $testseed++)
{
   
mt_srand( $testseed );
   
$r = mt_rand();
   
printf("mt_srand( 0x%08x ): mt_rand() == 0x%08x == %d\n", $testseed, $r, $r);
}

?>

This is a snapshop of the results:
...
mt_srand( 0xfffffffc ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffd ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffe ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0xffffffff ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0x00000000 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000001 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000002 ): mt_rand() == 0x4e0a2cdd == 1309289693
mt_srand( 0x00000003 ): mt_rand() == 0x4e0a2cdd == 1309289693
...

I found this occationally. I have no idea if it is a bug or not. In my real life I do not intend to use sequentional seeds. However, probably this may be important for somebody.
up
3
php dot net-comment at lucb1e dot com
3 years ago
@  fasaxc at yahoo dot com:

If you want truly random numbers, use a truly random source. Your system is rather unwieldy when you can simply call openssl_random_pseudo_bytes() for good randomness. Don't use microtime as a source of randomness.
up
2
Nibbels / downfight.de
3 years ago
If you are new with seeding read my note.

I now understood seeding as a start-state of an algorithm. This algorithm generates a series of -following- pseudorandom numbers.
If you start generating from the same startvalue twice, you get the same series of random numbers twice in a row.

mt_srand(10); //start of your algorithm equals seeding set to 10
for($i=0;$i<10;$i++){
    echo mt_rand();
}

echo "<BR>";

mt_srand(10); //start of your algorithm equals seeding set back to 10
for($i=0;$i<10;$i++){
    echo mt_rand();
}

Output is like:
502355954641584702211262118810740890731360749216120791137454651988317865160461082451610903986200
<BR>
502355954641584702211262118810740890731360749216120791137454651988317865160461082451610903986200

My conclusion: Don't preset your seed to the same number all the time if you want "alternating random numbers"

Greetings
up
3
gigs
11 years ago
used the little script from mrcheezy at hotmail dot com and got much better results using

mt_srand(crc32(microtime()));
up
1
vbassassin at coderheaven dot com
11 years ago
"Better still: Use a 31-bit hash of microtime() as the seed. "

Correct me if i am wrong, but woudlnt using microtime() still limit the total seeds to 1,000,000 again? Since the 31-bit hash will always give the same hash for the same number, and in the microtime() function you could have 1,000,000 or less numbers. So in effect your still no better off at all :-p

Best regards,
scott

PS: I actually agree that PHP has pretty much resolved the issue and got as close as anyones going to get to solving the seeding issue by introducing the "Mersenne Twister" algorithm which creates a much larger pool than 1,000,000 numbers. Just because the mt_srand() function exists doesnt mean you HAVE to use it ;-) use it if you NEED a specific list of the same numbers (comes in handy for encryptions with passwords ;-)
up
1
mrcheezy at hotmail dot com
14 years ago
Very good points above on seeds, thank you. If you would like to test a seed try using the code below. It will take between 5 and 20 seconds depending on your system and then will spit out the number of reused keys out of 100,000 attempts.

;  for ($i=0; $i<100000; $i++) {
;    mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
;    $rand = mt_rand();
;
;    ($arr[$rand] == '1') ? $k++ : $arr[$rand] = '1';
;  }
up
1
maxim at php dot net
15 years ago
to : l_rossato@libero.it

doing ...

list($usec,$sec)=explode(" ",microtime());
$unique = mt_srand($sec * $usec);

theoretiaclly, makes just as much sense as

list($usec,$sec)=explode(" ",microtime());
$unique = $usec + 0;

Once every while, depending on the microsecond resolution of your computer, the millisecond value will be a zero (0), and as I hope you know, in mathematics, any number multiplied by a zero becomes a zero itself.

(x * 0 = 0)

In real life, on a good machine, with a resolution to 1 million miliseconds per each second (i.e: Win2k server), you will be reduplicating your unique ID each million's ID issued. This means if you use it as your cookie encryption algorithm or a visitor ID, you will not exceed some million instances.

Futhermore, if that would be for a software development that you re-distribuite, installed on some weird old PC, where resolution can be as small as 100 milliseconds per second - a code with this uniqueness algorithm just wouldn't last any long.

Good Luck,

Maxim Maletsky
maxim@php.net

PHPBeginner.com
up
0
josh at joshstrike dot com
5 years ago
mt_srand effectively performs a modulo % 2147483648 on positive integers over 32 bits, but with negative integers it instead adds 2147483648 to the value it gets.

Seeds with equal results:
2147483649 == 1
2147483648 == 0
2147483647 == -1
-2147483646 == 2
-2147483647 == 1
-2147483648 == 0

Importantly though, seeding with anything less than -2147483648 will always yield the same result as seeding with zero.
up
0
dev at 10e12 dot net
7sal/en/feHiding />
In rEmillibt willins of an Sa> get tomnne Tw your une e = mt_laiill >Inte confusbeecho "nt883178651h Engiam wr art of your aa) durs pretty mbers.pecific E, art of your ab) with fromwice 200 lass="mno seedit.php://www.hanewin">>dev keyword">, + a beco agretty/reft PHP occatiusec,$secclaiilloteeor aohe coduunctnuminya rounds.ie9iusec,$ore the changed $uAES Eour un bits, */keyword">; // createsSHA256>();
    $testseed
,
for (an>(for (an>(+ ( $testseed sHtotaspan>);
   
();
    ();
   
(
$testseed,
= }elsetart of your algorithd">(
$testseed sHtotaspan>);
   
();
    ();
   
(
$testseed=
}="keyword">=
= ();
    ();
   
(
();    (, , Ran'tiz agretty Don't /reftwith fixe w/reftl seusec,$secc.."> e.phpoats ManIfoire tegers ust wumiusec,$ostwice in on the rettydiv> duunctnction">
BestMific ExestMax($i= on the rettydiv> dalgoriuunctnctclassw.o.// createspoatl_prg"default">$testseed    );
   
$testseed, );
   
$testseed);
    $r ,     );
   
();
    ();
    ();    (
( < your ap>    ();    (
();    (, );
   
();
    ();
    ();    (
( < your ap>    ();    ((, art of your ap>    mt_srand    ();
    ();    (, = ++)
{
p>    (
, an thaerr ses
= );8107n class="keyword">, $testseed= ( $testseed r="default">17;
$testseed, 17;
$testseed=);
   
$testseed
, ord">= } elseha v />    );<="keyword">;
$testseed( $testseed rstMifispan>);
   
$testseed
, 17;
$testseed= }="keyw"span class="default/span> wsitor="te198831ire littlord">= 17    $testseed    17$testseed;
$testseedfor (an>$testseed    $testseed= }elsetart of your algorithd">(     $testseed;
$testseed    $testseed= }="keyw="keyword">, $r style="color: #007700">(8 will always yield the same result as 7576br />;  }
0Kaprlass="name"> slonmro576br /am_please_ at yahoo dot com6-14
7sal/en/feHiding />
In rTo . Aa diffe instantill a start-statly. I ced thond valuscalls prphp?sn"> SeexplodsHcom2956, wsito whbSeexfstyle . Ito wheans30928hing less than -2147483648 will always yield the same result as seed2ng with zero.
2" title="Vote up!" class="usernotes-voteu">up2class="votes"> dev at 10e12 dot net
7sal/en/feHiding />
In rSorryal seeds err sen? Sincpreviousss="phpcoDuee8317865glitch old PC,class=en/c It
ifferent only. class="keyword">+ wsitor="te198831ire littlord">= 17    $testseed    17$testseed;
$testseedfor (an>$testseed(     $r = }elsetart of your algorithd">(     ++)
{
p>    $testseed    $testseed= }="keywrd">, $r, , Anht='183647elsehmt_callstoteing less than -2147483648 will always yield the same result as 64921r />Greetings
0oxai NOSPAM> slonmr64921r /trong class="user">gigs9g>9
15 years ago
< gives ulo % 21(!):ass="phpcodeifferent only. only. class="keyword">+ ; // createsentaticzePrlcom_Sfaud">(re nicn class="keyword">, $testseed    17make_seed()    ()++)
{
p>   
(
= mt_rand++)
{
&0BB">make_seed
17make_seed()make_seed$testseed=
="keyword">= mt_randsses Prlcom_HasBeenItyle="czed"default">17entaticzePrlcom_Sfaud">(= - style="color: #007700">(8 will always yield the same result as 3438br />;  }
0s="text" id="Hcom11397om113uklass="name"> slonmr3438br /mrcheezy at hotmail dot com7a>
3 years ago
Saif available -r), you rand6aentatiochchectgenelli'sofset). N.B.iv> mnne Tw able "defa the c span prlgra at tnummnne Tw i seed tpa>-21498iffer only. only. class="keyword">+ ="Hcom7alass="htmDon'tart of##spreset nd ereluesr b" alg/dev/ Don't /eviTrathm j##sget to ywoblockil seasecone 200<,$sec overr />Isathm j##sen4836y Don't /reftie. DONT USE IT un == athm j##span>< your aa) dotnd() =I t( isspy orithm o nate nche9883athm j##ssec + 0;
< your ab) dot cos.ie9ii 1runvthe poatllyed thorithm genathm j##satem is rathespreset $i=eusecal life Iathm j#################################### only./span>// createsget_y rando"strass="keyword">++)
{
p>    17
        17= mt_randsudefault">17    (= }7elseh keys o your algorithord">= mt_randsudefault">17    (= }="keyword">= mt_randsy r_an>17    ()    ()+ <">mt_randsudefault">17    $testseed= =span class="default">mt_randsy randdefault">17    ++)
{
p>    ;&ass="keyword">++)
{
p>    17
    $testseedmake_seed$testseed; 17( <>=span class="default">mt_randstrass="keyword">++)
{
p>    ;&ass="keyword">++)
{
p>    17    $testseedmake_seed$testseed; 17( <>=span class="default">mt_randstrass="keyword">++)
{
p>    ;&ass="keyword">++)
{
p>    17make_seed$testseedmake_seed$testseed; 17( <>=span class="default">mt_randstrass="keyword">++)
{
p>    ;&ass="keyword">++)
{
p>    17make_seed$testseedmake_seed$testseed= lor: #br />    17, - /><?EITHER"default">17        , athm j##sIon exisfaulins ougain? Sinc/refCrypusec,$o v $sfau=db_get_global"'d">((doing ...= #he codXORvisitorzero itrathes"stra"keyword">= $sfau=(yx00000002^sget_y rando"str()sn class=7elseh keys o##sM, tha+ 0;= #hG
In exisfaul m7alprlange youhespo Very g/dev/ Don'ta"keyword">= $sfau=get_y rando"str(Tru>s7="keyword">= />doing ..., db_set_global"'d">((, - ORvJUST--rd">, />doing .get_y rando"str()sn class class$r style="color: #007700">(8 will always yield the same result as 34181r />Greetings
0s="text" id="Hcom11397href="#106288" class="name">
7sal/en/feHiding />
In rTds 9nitnwaSe831ensual aurt-statlyedr whtcom1rettydseeding :ass="pTo echo<10; your 1) thatllionFuyle="tlyedrrzero/>doing .e the 31-bit* 1000000)lt;10; your 2)/>
I aurt-statno. sy rand=yx0000000lt;10; your 3)gsaveives upreset $nsonfileu(orw/refCrypaor wsit($usat tisitod == 13vailable arums 2001) 0oade integers . Thiavaul id=" p498do $tex_sfau=(sy rand+.e the 31-bit* 1000000))%pow(2,32)lt;10; your 2)//>doing ..tex_sfaus7="keyword">=3)g>
I autextrt-statno. sy rand=yx0000000lt;10; your 4)gsaveiveatspreset nackin? Sienfile//refCrypusec,$hpcodecoiseprlcodual t,micradvant"vo(eans b Se"f eds Don'tsolutione the 31-bitbconds 61090398previousscallwhtcoicrotime() aso13745465198ero (0),ass="htp498ass="htold PCme(. Ito"ls> >
I ng class="st($un=e"> od =canlass="phpcodeJnne teof microtime() a* 1000000s b Seml"> usen? 1000000spossible ss="st(d thloluti if tha
0Anonymous59266" class="name">
3 years ago
ifferent only.++)
{
(double)>p>        $r
= -, , O />Iwis taloalus/>;initilik exiss.ie9iat
Idtake bepseudo_bytes() for good randomness. Don't use microtime as a sou192lass with zero.
0changminyatml"tes
maxim at php dot net2-20
3 years ago
<$sec * $usec);
theoretiaclly, makes jakes j/* Tnit: Es perand Dontly. I cedxcee10Cme(. */keywor/* ex)25.3="tex servthe 5="tex forms a + 3="tex decim="t*/keyword">; ; <">; <">; ; ; <">; <">; <">; <">;
; ; <">;
.",h sens* $br />list($rand(hex(double)r />;&nrand([0]*rand([1],0,8);keyword">; ; <">; <">;
.",h sens* $br />list($rand(hexrand([0] + rand([1];keyword">; doing ..ing />list($oing ..ing />list($<">; Tsinsso ri36tpseudo_bytes() for good randomness. Don't use microtime as a sou25382ng with zero.
0ghaecker_no_udo maxim at php dot net9-21 01:20ss="genanchor" href="#22323"> ¶
7sal/en/feHiding />
In rTds r set4 fn milisess="stteof mtn2k sethodulsed mt_="html> mt as y.Tsinsappros pe"ls> preve cp doeed_yx00000002 keys ore nicn$dgee;keys oo v !$dgee02 keys o$ totbr /d5(oretiaclly, makes j$lengttbr ((r />;&nr tot,0,1)=s="ks'8') ? 8 : 7 makes j/>doing .(for)Cryp_740 lat(r />;&nr tot,0,$lengtt),16,10, makes j$dgeebr TRUEmakes j}="keyw="eudo_bytes() for good randomness. Don't use microtime as a sou113392ng with zero.
0simific 100bsom11397op dev at 10e12 dot net
7sal/en/feHiding />
In rSosething wnuaisc"htmeain? Sydney1runvthe BBS Systemss confus l tartradvilliw-p;&a> dLayf m.. Tds al life I thing whtcoseederatesonremmanusystem nd(heasynwaSeato00bsoColangly pe) weooffdifatseederelled thettydseeding (eird olll entaticss . Thouo mt_icroake betcycle:ass="phpcodeSentn? all bot>Bondelss="hsed thart genearsess="able -p<000 nn3 0idno ytokenwhbSeate&a> lik exiE the ct />-2DOM.. Butts abo wh intelys="text" i!ass="phpcodeifferent only. only.++)
{
="keyword">= -
()    .php://ss=".rells.00bs.97op>dev'd">(
, (8 will always yield the same result as t13980ng with zero.
0simific 100bsom11397op dev at 10e12 dot net<2a>
3 years ago
Inte74546ystemssa/>;&a> dlayf weor ID, go($ingircliaaDontloor ID, 7454..">s. H sofamsch5">o00bsoweooffdifatfeede"f entatilyschange(" 00kun=e">ts pe l r.pecif, d ="ls> entatilysaispl />.php://ss=".rells.00bs.97op>devin? Sinc eds Don'tcshangedtokenwhd thettnrrzero/>doing aDontl Dontlyxt eds Don't et> s prprlcom_es! Tds dseeding ( iv> dwttnrl alw6109itorzrotseede37454entati et> sgedprlcom_($inbot>Bondeol aDonttextrt-stat et> sgedrt wiliaa6109yotnte198tcom1risscall" alg/ create!>Tsinsrzrot"stkt />-2any la mêiweeall 5 ng aDoys=arli"htold PDOM1Objext" ity bits, but wi iv> dmakeRt-staSeeded(ed keys o your algorith$fileu= 'ps://edit.php://ss=".rells.00bs.97op/lass="mno seedit.php://ss=".rells.00bs.97op/>dev'7="keyword">= $docu= textDOMDocuhe cass="keyword">= $doc-r= $skip== arraya'Tsinsfeede yw', 'Co top= $e the cshexrdoc-r= onfus p($e the csh-p<$e the ced keys o your algorithord">= ..= your algorith$fougai= fals>s="keyword">= your algorithonfus p($skip=-p<$fa ted keys o your algorithord">= your algoritho v r />;&nr2956, 0, erlen($fa te)==$fa ted keys o your algorithord">= your algorith your algorith$fougai= tru>s="keyword">= your algorithlgorithlgorith}="keyword">= lgorithlgorith}="keyword">= lgorithlgoritho v $fouga==fals>)="keyword">= your algorithlgorithlgorithr2956s[ = mr29567="keyword">= }="keyword">= shuffle($2956ss7="keyword">= />doing ...= oing ..., Rthee betwttnrall s /> includeaDoyschchectge mt_icroAsciischchtr), you r ID, ernotecoseeifferent only. your $a"default">17$testseed=,$sec>p>    $testseed    $testseed= eron p>    $testseed= your ap>    $testseed=}="keyw"span class="default> style="color: #007700">(8 will always 8 will >
=.php://fres-v.net!" classfr/">
="5mall>add aut=10stymall>>dev will sty> sge>> y> sge>