Search code examples
perlprng

I need a portable, consistent pseudorandom number generator


I am writing a kid sister encryption function and I need a PRNG that produces consistent results across OSes (so no floating point math, taking advantage of hardware, or system level software). It would be nice, but not necessary, for the PRNG had a period longer than 230.

I am currently using a 32 bit Xorshift:

#!/usr/bin/perl

use strict;
use warnings;

{
    use integer; #use integer math
    my $x = 123456789;
    my $y = 362436069;
    my $w = 88675123; 
    my $z = 521288629;

    sub set_random_seed {
        $w = shift;
    }

    sub random { 
        my $t = $x ^ ($x << 11);
        $x = $y;
        $y = $z;
        $z = $w;
        my $rand = $w = ($w ^ ($w >> 19)) ^ ($t ^ ($t >> 8)); 
        return $rand % 256; #scale it back to a byte at a time
    }
}

set_random_seed(5);
print map { random(), "\n" } 1 .. 10;

But I am worried because I don't really understand how it works. For example, the original source did not have an ability to set the seed, so I added one, but I don't know if I chose the correct variable for the seed.

So, all of that boils down to

  1. Do you know of a module on CPAN that fits my needs?
  2. If not, do you know of an algorithm that fits my needs?

Solution

  • Math::Random::Auto is a CPAN module implementing the well-known Mersenne twister PRNG.