Repeatable Pseudo Random Number Generator (PHP)

I wrote a simple class to get repeatable random numbers out of an input seed.  I’ll post it here in case someone else would find such a thing useful.  It is based on SHA1 rounds. After a number of any kind is fetched, another round of SHA1 is applied.

Download it here: RepeatablePseudoRNG

The class has 3 different methods for retrieving random numbers.

Methods:

Constructor(seed [null])

Provide your initial seed when you instantiate a new object.

fetch_int(min, max)

Fetch an integer between min and max. This is inclusive and the max range is limited to 31 bits on most systems.

fetch_float(min,max)

Fetch a floating point number between min and max. Like, fetch_int, this is inclusive.

rand()

Fetch a floating point number between o and 1.  Also inclusive, though getting exactly 0 or 1 should be rare.

perform_rounds(roundcount)

Update the seed a specific number of times, without actually generating any numbers.

Usage example:

require 'rprng.php';
$rng = new RepeatablePseudoRNG('Totori');
//Generate some random numbers.
for($i = 0; $i < 10; $i++)
{
   echo $rng->fetch_int(1,10),"\n";
}

The above would output a list similar to the following each time it is run:

2
8
3
5
2
6
9
2
5
1

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>