Subject: | Better seeding and reporting the seed |
Hi,
Version 1.06 of Math::Random::MT::Perl added the option to return the
seed used when automatically seeding the pseudo-random number generator.
This feature is important to generate the same series of pseudo-random
numbers, but is currently lacking from Math::Random::MT.
In addition, the generation of the seed in Math::Random::MT::Perl is
such that several seeds generated automatically close in time will be
different, which is not the case of Math::Random::MT because is uses the
time() function, which is expressed in seconds. Again, having a better
seeding process would be nice.
Here is the current implementation of these features (in Perl) in
Math::Random::MT::Perl. I suppose that the srand() function can be used
as-is in Math::Random::MT, but the _rand_seed() function should probably
be re-implemented in C:
sub srand {
# Seed the random number generator, automatically generating a seed
if none
# is provided
my (@seeds) = @_;
if (not @seeds) {
$seeds[0] = _rand_seed();
}
$gen = Math::Random::MT::Perl->new(@seeds);
my $seed = $gen->get_seed;
return $seed;
}
sub _rand_seed {
# Create a random seed using Perl's builtin random number generator
system
my ($self) = @_;
# 1/ Seed Perl's srand() with a temporary random seed that varies
quickly
# in time so that no two identical seeds are obtained if several
seeds are
# automatically generated in a short time interval
my $tmp_seed = (gettimeofday)[1]; # time in microseconds
CORE::srand($tmp_seed);
# 2/ Generate the random seed to use using Perl's builtin rand()
(unsigned
# 32-bit integer)
my $max = int(2**32-1); # Largest unsigned 32-bit integer
my $rand_seed = int(CORE::rand($max+1)); # An integer between 0 and $max
return $rand_seed;
}