Initializing Perl's rand
dld at coyote.com.au
Thu Jun 27 10:36:45 EST 2002
On Mon, Jun 24, 2002 at 11:57:23PM +1000, Michael James wrote:
> Can anyone help me out here.
> I am using rand in perl.
> The book says it should get initialized (call srand) on the first invocation.
> Supposed to be true on any version 5.004 or after, and I'm using 5.6.1
> But my script just took the exact same random walk 3 times running,
> and I'm suspicious. I need runs to differ.
> Does perl initialize to the same seed each run?
> How can I make it get a different seed each run?
Hmm. Perl has implicitly called srand with _something_ (good, bad, best
available-on-platform, ...) for as long as I remember.
perl -e 'print rand()';
perl -e 'print rand()';
Prints two different values (at least on Unix, MacPerl OTOH..). If you're
not gathering billions of random numbers I'd try just leaving out the
srand() and rely on whatever the particular perl you're running has as a
compiled in default. Not knowing a good entropy source on the Mac, it's
probably better than any alternatives (especially since it was written in C
and has more access to the system than you do through Perl).
If you're using billions of random numbers, drand48() is about a tenth
the speed of some better algorithms (see Numerical recipes, subtractive
55-element array worked well for me), and isn't actually much faster than a
DES-based PRNG scheme. Layering Perl on top of that will lose an order or
two of magnitude in speed as well, so maybe it doesn't really matter that
drand48 is slow.
Another worry using rand() is the length of the mantissa - is it 32 bits
or 48 bits? If 32 bits, you don't want to use billions of them, or you're
likely to get some exact repeats and hit the extreme endpoints.
Divide-by-zero is one possible result, but even worse you can also end up
with step-size effects that you won't even know are there, or serial
correlations, or striping in N-dimensional space. Cheesy system PRNG's
aren't really suitable for scientific work without some additional layers.
drand48() isn't too bad (just slow), but native rand()/srand() are bad. If
you'd like a copy of some reimplementations of the NR routines (in C) let me
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Size: 307 bytes
Desc: not available
Url : http://lists.samba.org/archive/linux/attachments/20020627/f320ea55/attachment.bin
More information about the linux