Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Generating Repeatable Pseudorandom Sequences

by Anonymous Monk
on Sep 05, 2002 at 16:36 UTC ( #195433=note: print w/replies, xml ) Need Help??


in reply to Generating Repeatable Pseudorandom Sequences

For cases when you can't, or don't want to, rely on an external module, this is quick, simple, and good enough for non scientific computing:
sub make_random_generator {
    my ($seed, $min, $max) = @_;
    # DO NOT CHANGE THESE
    my $a = 7 ** 5;
    my $m = (2 ** 31) - 1;
    # if seed was zero this generator will return zeros 
    # forever, set it to some arbitrary value
    if ($seed == 0) { $seed = 12345678; }
    unless (defined $min) { $min = 0; }
    unless (defined $max) { $max = $m; }
    if ($max < $min) {
        my $t = $min;
        $min = $max;
        $max = $t;
    }
    return sub {
        $seed = ($a * $seed) % $m;
        # "scale" $seed to the range ($min,$max)
        return int ((($seed / $m) * ($max - $min)) + $min);
    }
}
use it like this:
for my $seq_n (1..10) {
    print "random sequence with seed $seq_n:\n";
    my $gen = make_random_generator(rand, 0, 1000);
    print join ", ", map { $gen->() } 1 .. 10;
    print "\n";
}
this will return the same 10 pseudo random sequences every time you run it.
  • Comment on Re: Generating Repeatable Pseudorandom Sequences

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195433]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2023-01-27 01:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?