working of rand in perl
How does the value produced by rand function depends on it seed value.When we do not define any seed then how does its values differ. Below is a code that i found for generating numbers for an integer array can any one please explain :
#!/usr/bin/perl -w
# Linear search of an array
# Note that if you later on want to search for something from a
# list of values, you shouldn’t ha开发者_如何转开发ve used an array in the first
# place.
# Generating 10 integers
$NUM = 10;
$MAXINT = 100; # 1 + the maximum integer generated
srand(); # initialize the randomize seed
print "Numbers Generated:\n(";
for $i (1 .. $NUM) {
push @array, sprintf("%d", rand(1) * $MAXINT);
print $array[$i-1];
print ", " unless ($i == $NUM);
}
print ")\n\n";
You don't need to explicitly call srand; it will be implicitly done for you the first time you call rand if you haven't previously called srand.
srand with no parameters will try to initialize the random number generator to a, err, random state. It uses /dev/urandom or the like if available and otherwise falls back on a value calculated from the current time and pid.
rand() with no parameters returns a floating point value between 0 (inclusive) and 1 (exclusive). Multiplying that by some integer number gives a floating point value from >= 0 and < that integer. Using that in integer context (such as a '%d' format value) gives you an integer from 0 to one less than your multiplier. rand(x)
, for x other than 0, returns the same range of random numbers that x * rand()
would have. So rand(1)
is equivalent to just rand()
, and rand(1) * $MAXINT
could have just been rand($MAXINT)
.
As far as I know perl uses the pseudo-random number generation functions of the standard C library.
It may depend on the implementation but it usually is a Linear Congruential Generator. This kind of PRNG uses its previous value to generate the next, therefore it will need a start value aka the seed.
The value of initializing with a selected seed is, that you get the same pseudo-random numbers. In that way you can keep some random based calculations repeatable, eg. how different alogrithms performs on a fixed set.
精彩评论