Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Random Number Generator

by Eily (Parson)
on Aug 19, 2013 at 22:53 UTC ( #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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1050096]
[karlgoethebier]: My perltidy adds a semicolon after .... How can i avoid this?
[LanX]: ellipse aka ... aka yadda yadda is a new command
[LanX]: sopw!

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2017-11-18 18:14 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (277 votes). Check out past polls.