(unknown)

Hi,

How to generate rand (random number) between two numbers?
I mean not between 0 and some number. It should be between some number (not 0) and some number.

Sincerely,
Asset

How to generate rand (random number) between two numbers?
I mean not between 0 and some number. It should be between some number (not 0) and some number.

def range_rand(min,max)
min + rand(max-min)
end

This is the generally utility function I use. Throw in srand with a seed if you're using it for something related to security.

Regards,
Chris White
http://www.twitter.com/cwgem

Also you can mod the number by the cardinality of your range and then add
your lower bound.

···

On Mon, Sep 19, 2011 at 12:46 PM, Chris White <cwprogram@live.com> wrote:

>
> How to generate rand (random number) between two numbers?
> I mean not between 0 and some number. It should be between some number
(not 0) and some number.

def range_rand(min,max)
  min + rand(max-min)
end

This is the generally utility function I use. Throw in srand with a seed if
you're using it for something related to security.

Regards,
Chris White
http://www.twitter.com/cwgem

That's not a workable approach:

09:56:29 Temp$ ruby19 -e 'p rand'
0.13646702557098767

So you need to use rand with an integer argument - and if you do that
there is no point in picking another value than the range size.
You'll end up with the solution Chris proposed.

Kind regards

robert

···

On Mon, Sep 19, 2011 at 7:34 PM, Karch <dimeneira@gmail.com> wrote:

Also you can mod the number by the cardinality of your range and then add
your lower bound.

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

My bad. I assumed errantly that ruby's rand would default return a rand
number bounded by int size.

Too much C++ for me :stuck_out_tongue:

Thanks for the correction!

In Christ,
Karch

···

On Tue, Sep 20, 2011 at 4:02 AM, Robert Klemme <shortcutter@googlemail.com>wrote:

On Mon, Sep 19, 2011 at 7:34 PM, Karch <dimeneira@gmail.com> wrote:
> Also you can mod the number by the cardinality of your range and then add
> your lower bound.

That's not a workable approach:

09:56:29 Temp$ ruby19 -e 'p rand'
0.13646702557098767

So you need to use rand with an integer argument - and if you do that
there is no point in picking another value than the range size.
You'll end up with the solution Chris proposed.

Kind regards

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/