[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Generating a random floating point number

jamiethehutt

7/12/2006 2:43:00 PM

I'm a Ruby newbie and I'm wondering if there's a simple way to generate
a random floating point number, I want to generate numbers between 0
and about 2-3.6 with the max changing each time (an example max would
be 3.26861475366199).

I'm hoping there's something simpler than generating an integer
(rand(3)) and then generating a point (rand(0.268)) and adding them
together...

Thanks for any advice you can give!

(I'm really loving Ruby, I rewrote some of my university Java work and
programs that took hours to write in Java were done in minutes!)

6 Answers

Tim Hammerquist

7/12/2006 3:26:00 PM

0

jamiethehutt <jamie@annforfungi.co.uk> wrote:
> I'm a Ruby newbie and I'm wondering if there's a simple way to generate
> a random floating point number, I want to generate numbers between 0
> and about 2-3.6 with the max changing each time (an example max would
> be 3.26861475366199).
>
> I'm hoping there's something simpler than generating an integer
> (rand(3)) and then generating a point (rand(0.268)) and adding them
> together...

Calling Kernel.rand with no argument yields a random floating point
number n where (0 <= n < 1). So:

my_number = rand * my_limit

....should help.

HTH,
Tim Hammerquist

Daniel DeLorme

7/12/2006 3:31:00 PM

0

jamiethehutt wrote:
> I'm a Ruby newbie and I'm wondering if there's a simple way to generate
> a random floating point number, I want to generate numbers between 0
> and about 2-3.6 with the max changing each time (an example max would
> be 3.26861475366199).

That's a pretty weird request, but you'd do something like this:
rand*(2+rand*1.6)

Daniel

khaines

7/12/2006 3:40:00 PM

0

jamiethehutt

7/12/2006 4:19:00 PM

0


Tim Hammerquist wrote:
> my_number = rand * my_limit

Thanks! That seems to be just what I need!

Jamiethehutt

Mauricio Fernández

7/12/2006 6:35:00 PM

0

On Thu, Jul 13, 2006 at 12:39:50AM +0900, khaines@enigo.com wrote:
> def fp_rand(limit)
> fl = limit.floor
> rm = limit.remainder(fl)
> rand(fl) + rand(rm)
> end
>
>
> fp_rand(12.73)
> => 10.1895547681143

<nitpicking>
That method would never return values whose decimal part >= 0.73 in the above
example.
Besides, the variance of the resulting random variable would be lower than
for the correct limit * rand():
(fl^2 + rm^2) / 12 instead of (fl + rm)^2 / 12 = limit^2 / 12
</nitpicking>

--
Mauricio Fernandez - http://eige... - singular Ruby

khaines

7/12/2006 7:18:00 PM

0