Forum Moderators: coopster & phranque

Message Too Old, No Replies

Random in a range (perl)

         

littleman

2:32 am on Feb 8, 2001 (gmt 0)



Ok I derived this from a devshed article, but I know there must be a way to do this in a less convoluted manner:
#!/usr/bin/perl
$lower = 50;
$upper =100;
while ($random < $lower)

{

$random = int(rand($upper));

}
print $random;

Any suggestions?

Brett_Tabke

7:58 am on Feb 8, 2001 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



That is near what I've always used.
If you are using larger numbers, this is faster than the while loop:

$low=50;
$high =50000;
loop: $rnum =rand($high);
goto loop if $rnum < $low;
$rnum =int($rnum);

I've never tried it with the ? : type if syntax, but I don't believe it would be faster.

(and your right...there has to be a better way).

sugarkane

9:34 am on Feb 8, 2001 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Another way would be like this:

$lower=50;
$upper=100;

$upper2=$upper-$lower;
$number=int(rand($upper2);
$number=$number+$lower;

Added:
Which could be scrunched down to

$number=int($lower+rand($upper - $lower));

Brett_Tabke

9:42 am on Feb 8, 2001 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Good tip SugarKane. That was one I'd used in the past and forgot all about.

littleman

5:04 am on Feb 10, 2001 (gmt 0)



:) thanks!

littleman

10:56 pm on Oct 11, 2001 (gmt 0)



thanks again!:)

netcommr

2:49 am on Oct 15, 2001 (gmt 0)

10+ Year Member



random numbers in a range:

rand(b - a) + a

[added after brain thaw]
...which is of course what sugarkane wrote (had to look at it again, been a long day)