Generating random numbers in Perl

jgbishop

Senior member
May 29, 2003
521
0
0
I'd like to generate a random number in Perl between 20 and 80. Anyone know how this is done?

I know I should use srand() to seed the random number generator, and I can use rand() to get a number. But how do I restrict it between 20 and 80 (inclusive)?
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
rand (x)

will generate a random number between 0 and x

so you can add 20 to the result to generate random number between 20 and x
 

UCJefe

Senior member
Jan 27, 2000
302
0
0
Originally posted by: jspsh
dont forget to seed it by putting srand; at he top of the script

perldoc -f rand

rand EXPR
rand Returns a random fractional number greater than or equal to "0"
and less than the value of EXPR. (EXPR should be positive.) If
EXPR is omitted, the value "1" is used. Automatically calls
"srand" unless "srand" has already been called.
See also
"srand".
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
If you're trying to generate a random INTEGER between 20 and 80 (inclusive), then:
int (rand (60) + 20.5);
will work fine.

If you're trying to generate a random decimal number between 20 and 80, you can't have it be inclusive for 80.