Generating a random floating point number

J

jamiethehutt

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!)
 
D

Daniel DeLorme

jamiethehutt said:
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
 
K

khaines

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!

def fp_rand(limit)
fl = limit.floor
rm = limit.remainder(fl)
rand(fl) + rand(rm)
end


fp_rand(12.73)

=> 10.1895547681143


Kirk Haines
 
M

Mauricio Fernandez

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>
 
K

khaines

<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>

Thanks, Mauricio. It's always good to have one's nits picked on
occasion. :)


Kirk
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top