I am trying to use srand function in perl but seems that its not setting the seed value every often
#!/usr/bin/perl
srand(45);
$int = rand(50);
print "random integer is $int\n";
[root@localhost cookbook]# perl p2.7.pl
random integer is 17.8465963028886
Shouldn't the random number be something between 45 and 50?
The srand seeds the random number generator. Random numbers in most programming languages aren't truly random, but that's okay for most purposes. Setting a seed will allow the random number sequence to repeat over and over. From the Perldoc:
[T]here are a few situations where programs are likely to want to call
srand
. One is for generating predictable results, generally for testing or debugging. There, you usesrand($seed)
, with the same$seed
each time.
Here's a sample program:
#! /usr/bin/env perl
#
use strict; # Lets you know when you misspell variable names
use warnings; # Warns of issues (using undefined variables
use feature qw(say);
srand 10;
for my $count ( (1..6) ) {
say rand 10;
}
Every time I run it, I get:
$ test.pl
8.78851122762175
7.95806622921617
4.80827281057042
5.25673258208322
4.59162474505394
9.45475794360377
Over and over. That's because I'm using the same seed each time, allowing the random number function to repeat over and over. This can be useful in testing.
Get rid of that srand 10
line, and the program generates a different sequence of random numbers each time.
According to Perldoc rand:
Returns a random fractional number greater than or equal to 0 and less than the value of EXPR, [the argument given]. EXPR should be positive.
It continues:
Apply
int()
to the value returned byrand()
if you want random integers instead of random fractional numbers. For example,int(rand(10))
returns a random integer between0
and9
, inclusive.
So, rand 50
returns a value between 0 and 50 (but not 50). Saying, int( rand 50 )
will return an integer between 0 and 49. If I want a number between 45 and 50, I would have to first decide if 50 should be one of the numbers I want. If it is, I need a range of six numbers (45, 46, 47, 48, 49, 50). Thus, I want to use int( rand 6 )
to give me an integer between 0 and 5. Then I want to add 45 to that to give me a range of 45 to give me a range of 45 to 50:
say 45 + int( rand 6 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With