Generating random numbers?

Speaking of random numbers… I encountered a problem this morning with
them.

My problem is that I am getting the same “random number” repeated in
sequence. For example, my code looks something like this

100.times{
rand = Kernel.rand( 50 )
#do something with the random number
}

And I end up getting a sequence of random numbers like this:
5,5,5,5,5,5,5,5,89,89,89,89,89,2,2,2,78,78,78,78,44,44,44,44,44… etc

Strangely enough, doing the following in IRB does not replicate the problem:

100.times{
puts Kernel.rand(100)
}

nor does $> ruby -e ‘100.times{ puts Kernel.rand(100) }’

BTW, I am using 1.8.0.

Matt

I’ve tried seeding it each time with Time.now.usec, but that seems to make
it worse (which makes sense, because it probably takes less than a micro
second between each generation).

Any suggestions?

···

From: “Brandon D. Valentine” brandon@dvalentine.com
Reply-To: ruby-talk@ruby-lang.org
To: ruby-talk@ruby-lang.org (ruby-talk ML)
Subject: Re: Generating random numbers?
Date: Tue, 29 Jul 2003 06:31:34 +0900

On Tue, Jul 29, 2003 at 06:19:58AM +0900, Harry Ohlsen wrote:

Can someone remind me of the name for the class/method for generating
random
numbers? I did a quick grep through the library and a google, but all I
found was a project that plans to improve the random number
generator(s).

Kernel::rand

Seed it via:

Kernel::srand

HTH,

Brandon D. Valentine

brandon@dvalentine.com
http://www.geekpunk.net
Pseudo-Random Googlism: texas is the reason do you know who you are?


Add photos to your messages with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail

Hi,

···

In message “Re: Generating random numbers?” on 03/07/30, “Orion Hunter” orion2480@hotmail.com writes:

My problem is that I am getting the same “random number” repeated in
sequence. For example, my code looks something like this

100.times{
rand = Kernel.rand( 50 )
#do something with the random number
}

And I end up getting a sequence of random numbers like this:
5,5,5,5,5,5,5,5,89,89,89,89,89,2,2,2,78,78,78,78,44,44,44,44,44… etc

No one can answer for you unless you reveal “something with the random
number”. This is the first report of such randomness problem.
I suspect a bug in your code.

						matz.

I’ve tried seeding it each time with Time.now.usec, but that
seems to make
it worse (which makes sense, because it probably takes less than a micro
second between each generation).

Any suggestions?

Call srand once, or don’t call it at all.