Re: rand(), mt_rand() and limits
| From: | Andrea Faulds | Date: | Mon, 12 Jan 2015 00:05:51 +0000 |
| Subject: | Re: rand(), mt_rand() and limits | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-80389@lists.php.net to get a copy of this message | ||
Hey Yasuo and Jordi,
> On 11 Jan 2015, at 23:56, Jordi Boggiano <j.boggiano@seld.be> wrote:
>
> On 11/01/2015 22:12, Andrea Faulds wrote:
>> * Make mt_srand() and srand() do nothing and produce a deprecation notice
>
> That is the only point with which I disagree. Looking at
> http://3v4l.org/FLHBV we see that while indeed across PHP versions
> the result has not always been the same, it generally is, and especially within one given version
> setting a seed means you get predictable results.
>
> This has benefits in some cases like fixtures generation where it might not be important if the
> output changes when you upgrade PHP, but you don't want entirely different fixtures every
> single time. Obviously if we could guarantee the algo won't change it would be even better.
>
> Bottom line is I think it's important to have the ability to set the seed yourself.
>
> On 11 Jan 2015, at 23:57, Yasuo Ohgaki <yohgaki@ohgaki.net> wrote:
>
> However, I object removal of srand.
> Game programmers need "the same random sequence" on occasion.
> There should be srand to get the same sequence for repeatable behaviors.
>
> rand()/srand() may be renamed to sys_rand()/sys_srand() (or whatever
> suitable name for them) in case user needs system random sequence
> for whatever reasons. I don't insist to keep system's rand/srand, though.
I don’t disagree with having some mechanism for predictable random number generation from a seed,
but I think the global random number generator is the wrong place to do it. It’s not guaranteed to
be predictable, and everything uses it, so some library you’re using might advance it without you
realising.
Much better would be to add a new, OOP API that gives you your own number generator (no global
state) and requires explicitly specifying the algorithm (cross-version compatibility), with a
guarantee that it won’t break in new PHP versions.
Something like this, maybe:
$numgen = new RandomNumberGenerator(RAND_MERSENNE_TWISTER, time()); // could auto-seed with
time()
$randInt1 = $numgen->getInt(0, 100); // gets random integer and advances this generator
list($randInt2, $numgen) = $numgen->newGetInt(0, 100); // gets random integer and returns a
new, advanced generator
$serialised = $numgen->serialiseState(); // Or maybe $numgen->getSeed() ?
Does that work?
--
Andrea Faulds
http://ajf.me/