PHP.mk документација

srand

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.srand.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.srand.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
srand

Референца за `function.srand.php` со подобрена типографија и навигација.

function.srand.php

srand

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

srandПоставете го генераторот на случајни броеви

= NULL

srand(?int $seed = null, int $mode = MT_RAND_MT19937): void

Го иницијализира генераторот на случајни броеви со seed или со случајна вредност ако не е seed дадено.

Забелешка: Нема потреба да го иницијализирате генераторот на случајни броеви со srand() or mt_srand() бидејќи ова се прави автоматски.

Безбедност: стандардниот сет на знаци

Бидејќи моторот Mt19937 („Mersenne Twister“) прифаќа само еден 32-битен цел број како семе, бројот на можни случајни низи е ограничен само на 232 (т.е. 4.294.967.296), и покрај огромниот период од 2 на Mt1993719937-1.

Кога се потпирате на имплицитно или експлицитно случајно сеење, дупликатите ќе се појават многу порано. Се очекуваат дупликатни семиња со 50% веројатност помалку од 80.000 случајно генерирани семиња според проблемот со роденденот. 10% веројатност за дупликат семе се случува по случајно генерирање на околу 30.000 семиња.

Ова го прави Mt19937 несоодветен за апликации каде што дупликатните низи не смеат да се случат со повеќе од занемарлива веројатност. Ако е потребно репродуктивно сеење, и двата Random\Engine\Xoshiro256StarStar and Random\Engine\PcgOneseq128XslRr64 моторите поддржуваат многу поголеми семиња кои веројатно нема случајно да се судираат. Ако репродуктивноста не е потребна, Random\Engine\Secure моторот обезбедува криптографски сигурна случајност.

Забелешка: Од PHP 7.1.0, srand() е направен нодум од mt_srand().

Параметри

seed

Ја исполнува состојбата со вредности генерирани со линеарен конгруентен генератор кој беше иницијализиран со seed интерпретиран како 32-битен цел број без знак.

Враќа seed е изоставен или null, ќе се користи случаен 32-битен цел број без знак.

Вратени вредности

Не се враќа вредност.

Дневник на промени

Верзија = NULL
8.3.0 seed сега е null.
7.1.0 srand() е направен новата функција mt_srand().

Види Исто така

  • rand() - Генерирај случаен цел број
  • getrandmax() - Прикажи најголема можна случајна вредност
  • mt_srand() - Го иницијализира генераторот на случајни броеви Mersenne Twister

Белешки од корисници 13 белешки

Niels Keurentjes
пред 15 години
Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code.
harmen at no dot spam dot rdzl dot nl
пред 16 години
To generate a random number which is different every day, I used the number of days after unix epoch as a seed:

<?php  
   srand(floor(time() / (60*60*24)));
   echo rand() % 100;
?>

My provider upgraded the php server recently, and calling srand(seed) does not seem to set the seed anymore. To let srand set the seed, add the following line to your .htaccess file

php_value suhosin.srand.ignore 0 

Kudos to doc_z (http://www.webmasterworld.com/php/3777515.htm)

Harmen
rjones at ditzed dot org
figroc at gmail dot com
Use the srand() seed "(double)microtime()*1000000" as mentioned by the [email protected] at the top of these user notes.

The most notable effect of using any other seed is that your random numbers tend to follow the same, or very similar, sequences each time the script is invoked.

Take note of the following script:

<?php
  srand($val);

  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20);
?>

If you seed the generator with a constant, say; the number 5 ($val = 5), then the sequence generated is always the same, in this case (0, 18, 7, 15, 17) (for me at least, different processors/processor speeds/operating systems/OS releases/PHP releases/webserver software may generate different sequences).

If you seed the generator with time(), then the sequence is more random, but invokations that are very close together will have similar outputs.

As [email protected] above suggests, the best seed to use is (double) microtime() * 1000000, as this gives the greatest amount of psuedo-randomness. In fact, it is random enough to suit most users.
In a test program of 100000 random numbers between 1 and 20, the results were fairly balanced, giving an average of 5000 results per number, give or take 100. The deviation in each case varied with each invokation.
edublancoa at gmail dot com
21 години пред
Another use of srand is to obtain the same value of rand in a determined time interval. Example: you have an array of 100 elements and you need to obtain a random item every day but not to change in the 24h period (just imagine "Today's Photo" or similar).
<?php
$seed = floor(time()/86400);
srand($seed);
$item = $examplearray[rand(0,99)];
?>
You obtain the same value every time you load the page all the 24h period.
contact at einenlum dot com
пред 2 години
Keep in mind that now srand is an alias for mt_srand, but they behaved differently before. This means you should not follow the documentation of srand, but the one of mt_srand, when using srand.

To reset the seed to a random value, `mt_srand(0)` (or `srand(0)`) doesn't work. It sets the seed to 0. To reset the seed to a random value you must use `mt_srand()` (or `srand()`).

<?php

$arr = [0, 1, 2, 3, 4];

srand(1); // or mt_srand(1) as they are now aliases
$keys = array_rand($arr, 2); // not random as expected

srand(0); // or mt_srand(0) as they are now aliases
$keys = array_rand($arr, 2); // not random either!

srand(); // or mt_srand() as they are now aliases
$keys = array_rand($arr, 2); // random again

?>
bootc at bootc dot net
20 години пред
OK, to summarize what people have been saying so far:

1. DO NOT seed the RNG more than once if you can help it!
2. You HAVE TO seed the RNG yourself if you are using PHP < 4.2.0.
3. Using a prime multiplier to microtime() probably does very little. Use the Mersenne Twister instead.
4. You can use the Mersenne Twister PRNG with the mt_rand and mt_srand functions. This is faster and is more random.
mlwmohawk at mohawksoft dot com
figroc at gmail dot com
srand() is pretty tricky to get right. You should never seed a random number generator more than once per php process, if you do, your randomness is limited to the source of your seed.

The microtime function's micro-seconds portion has a very finite resolution, that is why the make_seed function was added to the document. You should never get the same seed twice.

In the later CVS versions, PHP will seed the random generator prior to performing a rand() if srand() was not previously called.
Анонимен
figroc at gmail dot com
I have a ramdon circulater that changes a piece of text once a day, and I use the following code to make sure the see is unique enough.

$tm = time();
$today = mktime(0, 0, 0, (int)date("n", $tm), (int)date("j", $tm), (int)date("Y", $tm));                                                   
srand($today / pi());

The pi works wonders for the whole thing and it works like a charm. Any other big decimal number will do as well, but pi is the most common "big" number.
akukula at min dot pl
figroc at gmail dot com
Calling srand((double)microtime()*1000000),
then $a=rand(1000000,9999999), then srand((double)microtime()*$a)
adds nothing to the entrophy: the execution time of rand and srand is
constant, so the second microtime() produces nothing really fascinating. You may safely use just the first srand().
rjones at ditzed dot org
figroc at gmail dot com
As a sidenote on the usage of srand():

If you are making use of modular programming, it is probably better to try and call the srand routine from the parent script than from any modules you may be using (using REQUIRE or INCLUDE).
This way you get around the possibility of calling srand() more than once from different modules.

The flaw in this solution, of course, is when using modules produced by another programmer, or when producing modules for another programmer.
You cannot rely on another programmer calling the srand function before calling the modular function, so you would have to include the srand function inside the module in this case.

If you produce modules for use by other programmers then it is good practice to documentise the fact you have already called the srand function.
Or if you use a modular function produced by someone else, check their documentation, or check their source code.
MakeMoolah at themail dot com
yasuo_ohgaki at hotmail dot com
Sorry about that...  ok, forget have of what I said up there ^.

The code that would prove my example is this:

<?php
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
?>

Each time you SHOULD get the same answer, but if you did this:

<?php
srand(5);
echo(rand(1, 10));
echo(rand(1, 10));
echo(rand(1, 10));
?>

then the answers would be different, and you'd be letting the random number formula do it's duty.
hagen at von-eitzen dot de
yasuo_ohgaki at hotmail dot com
It is REALLY essential to make sure that srand is called only once.
This is a bit difficult if the call is hidden somewhere in third-party code you include. For example, I used a standard banner script that *seemed* to work well putting
three random banners in one frame. But in the long run, the choice appeared
somewhat biased - probably because srand was called once per banner, not
once per run.
It would be nice if the random number generator worked like in PERL: If You use the random function without having called srand ever before in a script,
srand is invoked before (and automatically with a nice seed, hopefully).
I suggest that one should do something like this:

<?php
if (!$GLOBALS["IHaveCalledSrandBefore"]++) { 
  srand((double) microtime() * 1000000);
}
?>

(Depending on the situation, one might also work with a static variable instead)
Glauco Lins
пред 10 години
srand and mt_srand are both initialized only once per process ID.

You cannot re-seed your rand algorithms after the first "srand", "mt_srand", "rand", "mt_rand", "shuffle", or any other rand-like function.

I have been facing an issue where after forking my process, all childs were generating exactly the same rand values.
This was due a first "shuffle" call on the parent process, so I could not re-seed the childs.

To solve my issue, I simple called "rand" N times, to offset the child rand generators.

# Offset the child rand generator by its PID
$n = (getmypid() % 100) * (10 * abs(microtime(true) - time()));
for ($n; $n > 0; $n--) {
      rand(0, $n);
}

Since each pcntl_fork takes a while to be completed, the microtime offers an extra offset, other than one PID increment.

This small code will make at the WORST hypothesis 1000 iterations.
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.