in reply to random question

I'm finding a random-number generator that relies on the built-in rand() and srand() quite odd. As the others have told you, you should not call srand() more than once in the program, and it's probably better to not call it at all! (Perl has done that for you already.)

Anyway, here's a simple one that returns numbers in the range 0..65535:

use Digest::SHA 'sha384_hex'; my $rng = generate_rng('salty' . localtime() . $$); print $rng->(), "\n" for 0..100; sub generate_rng { my $seed = shift; return sub { $seed = sha384_hex($seed); my $rnd = hex(substr($seed, 0, 4)); return $rnd; }; }

For further study, you might want to look at OpenBSD's rand() which is about as simple as it gets. (It's also a poor one; its use is discouraged.)

Replies are listed 'Best First'.
Re^2: random question
by Anonymous Monk on Sep 09, 2013 at 18:48 UTC
    I think there's a minuscule probability that this RNG leaves (at least) one number never to generate, shortening its ideal cycle. Potential fix:
    sub generate_rng { my $seed = shift; my $count = 0; return sub { $seed = sha384_hex($seed . $count++); my $rnd = hex(substr($seed, 0, 4)); return $rnd; }; }

    Take my methods with a grain of salt since I'm an amateur at best in this subject -- I wouldn't know a bad RNG from a good one.

    Anyway, it appears that the OP is trying to increase the randomness of rand() by various voodoo methods. This is a futile task and he's much more likely to worsen it by making it more biassed. For example, a lot of newbies try to out-random random by saying rand() + rand() and getting a triangular distribution as a result.