More info about the rand() function ?

cerbere

New Member
Messages
51
Reaction score
1
Points
0
Hello everyone,

I want to generate random integers in Perl, to be used as
array indexes. Let's say my array size is 10, so I want to
get evenly distributed integers between 0 and 9.

If I use

$index = int(rand(10));

is there a chance (however slight) that I will eventually
get 10 as $index ? That would be out of bounds, and we all
hate that... Of course, something like

if($index == 10) { $index = 9; }

will fix it but it hurts my feelings about elegant programming :pigeon:)

So the bottom line of my question is : can rand(n) ever
return n in Perl (or PHP) ?

PS : You can see a distribution of 100000 calls to rand()
at : http://ixedix.x10hosting.com/
(hit the "rand() test" button at bottom, then refresh
to get new distributions)

PPS : Where is the darn "Close thread" checkbox that the
sticky message begs us to use ? Can't find it on my browser.
 

scopey

New Member
Messages
62
Reaction score
0
Points
0
Calling rand() 100000 times will use a fair bit of CPU.

In php, the syntax for rand() is:

rand((int) min, (int) max);

So if I put rand(0,10) there should be a 1/11 chance that it will be 0, and a 1/11 chance that it will be 10.

Also, the server your site is hosted on is down -.- (absolut?).

Also, the close thread button is located by clicking edit on your post, clicking 'Go Advanced', then it will be below the textarea. (Edit - Or at the very top of the page.)
 
Last edited:

cerbere

New Member
Messages
51
Reaction score
1
Points
0
After further reading, I found that rand(expr) returns a
random number between 0 (inclusive) and expr (EXCLUSIVE).

So the right way to get uniformly distributed integers
between 0 and n - 1 in Perl is effectively

$rand_int = int(rand($n));

This is guaranteed to NEVER return $rand_int == $n;

Thanks for the reply about closing a thread, scopey,
but I can't even find the "edit" button. Maybe I need
a new browser !

ADMIN, PLEASE CLOSE THIS THREAD.
 

Salvatos

Member
Prime Account
Messages
562
Reaction score
1
Points
18
Yea the edit button has strangely disappeared for me too... Well in former posts, not on this one apparently ^^
 
Last edited:

vol7ron

New Member
Messages
434
Reaction score
0
Points
0
You shouldn't be so hasty to close.


After further reading, I found that rand(expr) returns a
random number between 0 (inclusive) and expr (EXCLUSIVE).
This is correct. rand(num) generates a range of values between 0 and that number, but not including the number.

So the right way to get uniformly distributed integers
between 0 and n - 1 in Perl is effectively

$rand_int = int(rand($n));

Yes and no. It's the only way to do from 0..(n-1). The function does what it's meant to do. Usually, a person would opt to include the upper bound, but not include 0. You might see something like:
$rand_int = int(rand($n))+1; # random number 1..n

That way the range of values is 1 to N.
 
Top