From: Matthew Kerwin Date: 2013-03-07T17:30:05+09:00 Subject: Re: Random#rand_inclusive? --90e6ba308f081b8c8504d7518369 Content-Type: text/plain; charset=ISO-8859-1 OTOH, without looking up exactly what Epsilon is (the smallest possible absolute interval represented by a float?), wouldn't your technique fail if max is big, because {big float} + {small float} = {big float} ? I'd suggest something clever with Rationals, personally, along the lines of `(max*rand(range+1))/range" Sent from my phone, so excuse the typos. On Mar 7, 2013 5:56 PM, "Robert Feldt" wrote: > Hi, > > Random#rand and Kernel#rand are exclusive i.e. they return a value >= 0.0 > but the max? Would any of the below approaches guarantee to give an inclusive > range? > > class Random > # Return a random number between 0 (inclusive) and max (inclusive). > def rand_incl(max = 1.0) > if Float === max > rand(max+Float::EPSILON) > elsif Integer === max > rand(max+1) > end > end > > # Same but with other strategy > def rand_incl2(max = 1.0) > if Float === max > num_floats = (max - min)/Float::EPSILON > min + rand(1+num_floats.to_i) * Float::EPSILON > elsif Integer === max > min + rand(max+1-min) > end > end > end > > Thanks in advance, > > Robert Feldt > > --90e6ba308f081b8c8504d7518369 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable

OTOH, without looking up exactly what Epsilon is (the smallest possible = absolute interval represented by a float?), wouldn't your technique fai= l if max is big, because {big float} + {small float} =3D {big float} ?=A0 I= 'd suggest something clever with Rationals, personally, along the lines= of `(max*rand(range+1))/range"

Sent from my phone, so excuse the typos.

On Mar 7, 2013 5:56 PM, "Robert Feldt"= <robert.feldt@gmail.com&g= t; wrote:
Hi,

Random#rand and Kernel#rand are exclusive i.e. they = return a value >=3D 0.0 but <max if max is a Float. What if one wants= a rand that is inclusive of the max? Would any of the below approaches gua= rantee to give an inclusive range?

class Random
=A0 # Return a random numbe= r between 0 (inclusive) and max (inclusive).
=A0 def rand_incl(ma= x =3D 1.0)
=A0 =A0 if Float =3D=3D=3D max
=A0 =A0 =A0 r= and(max+Float::EPSILON)
=A0 =A0 elsif Integer =3D=3D=3D max
=A0 =A0 =A0 rand(max+1)<= /div>
=A0 =A0 end
=A0 end

=A0 # Same= but with other strategy
=A0 def rand_incl2(max =3D 1.0)
=A0 =A0 if Float =3D=3D=3D max
=A0 =A0 =A0 num_floats =3D (max - min)/Float::EPSILON
=A0 = =A0 =A0 min + rand(1+num_floats.to_i) * Float::EPSILON
=A0 =A0 el= sif Integer =3D=3D=3D max
=A0 =A0 =A0 min + rand(max+1-min)
=
=A0 =A0 end
=A0 end
end

Thanks in advance,

Robert Feldt

--90e6ba308f081b8c8504d7518369--