Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reproducible random number series

Tags:

php

random

How can i get a series of reproducible pseudorandom numbers in PHP?

In older versions of PHP i could do that just by using the same seed in the RNG, but it does not work anymore since PHP has changed the way rand and mt_rand works.

Please also see this comment in PHP.net page:

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.

link of that comment: http://www.php.net/manual/en/function.srand.php#102636

Is there any solution ready? I do not have the time nor the experience to create my own pseudo-random generator code.

My goal is to have a code

<?php
   //( pseudo random code here...)
   $the_seed = 123; // 123 is just a number for demo purposes, NOT a static number
                    //...i hope you get the idea. It's just a hardcoded seed,
                    // it could be a seed based on a user-id, a date etc...
                    // we need the same output for a given seed.
   //( pseudo random code here...)

   // ...and finally
   echo $the_random_number;
 ?>

so everytime i visit this page i should get the same number.

like image 947
Sharky Avatar asked Nov 09 '11 17:11

Sharky


2 Answers

If you don't need a high quality output, the Lehmer RNG is about as simple as it gets. It was one of the algorithms could have been used by srand() internally (depending on your operating system).

$seed = 42; // any integer, maybe a database id

// init Lehmer RNG
$seed = $seed % 2147483647;
if ($seed <= 0) $seed += 2147483646;

// generate as many random numbers as you need
$seed = $seed * 48271 % 2147483647;
print($seed);

$seed = $seed * 48271 % 2147483647;
print($seed);

$seed = $seed * 48271 % 2147483647;
print($seed);

$seed = $seed * 48271 % 2147483647;
print($seed);
...

You can constrain the output to a range with:

$min = 0;
$max = 9;
print($min + ($seed % $max));
like image 122
Abhi Beckert Avatar answered Oct 13 '22 13:10

Abhi Beckert


The Mersenne Twist is a nice fast PRNG and here's a public domain PHP implementation for it:

http://kingfisher.nfshost.com/sw/twister/

That only works on PHP 5.3.0 and above.

like image 22
Adam Davis Avatar answered Oct 13 '22 12:10

Adam Davis