Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Random Number Generator

by Eily (Monsignor)
on Aug 19, 2013 at 22:53 UTC ( [id://1050096]=note: print w/replies, xml ) Need Help??


in reply to Random Number Generator

# [...] rand funct is time based
Well ... it might be. The random function has to be initialized with something randomish like the time (but it can also be the position of the mouse, or how much it has moved since start up, the mean typing speed of the user in milliseconds when he entered his password, etc ...), but initialization is only done once. You can check rand's documentation, which tells that srand is called, unless it has already been done. So after your first rand, the time does not change anything. You are actually just wasting time there.

Do not call srand() multiple times in your program unless you know exactly what you're doing and why you're doing it. [...]. Just do it once at the top of your program, or you won't get random numbers out of rand()!
This means that you should probably trust rand to be random enough for you, and not try to affect its behavior by messing with it. srand's documentation advises you to have a look at Math::TrulyRandom if you think rand does not do its work properly.

Using rand until you have a number that fits your expectation isn't a very good idea either, that's wasting time again. If you want to make sure you have a number that's n digit long, without leading 0, you could just do :

my $n = 10; my $lastDigits = int rand(10**($n-1)); my $firstDigit = 1+int(rand(9)); my $number = $firstDigit.$lastDigits; print $number;

Replies are listed 'Best First'.
Re^2: Random Number Generator
by hardburn (Abbot) on Aug 20, 2013 at 18:24 UTC

    I was actually researching this issue recently. It turns out that by default, Perl calls srand() with /dev/random (or an equivalent on your platform). Timestamps aren't involved. See util.c and search for Perl_seed.


    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2024-04-26 05:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found