I had similar thoughts a while back. I decided that extending Kernel =20
and mimicing the behavior of rand was the way to go. My code follows:
Regards, Morton
------ code starts
#!/usr/bin/ruby
# Extend Kernel with an enhanced uniform random number generator.
# Has the same behavior as rand for a single argument.
module Kernel
URAND_ARG_ERR =3D "Arguments not valid for urand"
# Return a pseudo-random number in the range 0.0...1.0, 0...m, or =20=
m..n.
def urand(m=3D0, n=3Dnil)
case m
when Range
m, n =3D m.begin, m.end
when Integer
return rand(m) if n.nil?
else
raise ArgumentError, URAND_ARG_ERR
end
raise ArgumentError, URAND_ARG_ERR if n < m
m + rand(n - m + 1)
end
end
# Now for a little testing ...
def test(times, m=3D0, n=3Dnil)
r =3D Array.new(times)
if n.nil? then
if m =3D=3D 0 then r.collect! {urand}
else r.collect! {urand(m)}
end
else r.collect! {urand(m, n)}
end
p r
end
test(3) # =3D> [0.0403243284672499, 0.875487065408379, =20
0.142408860381693]
test(3, 11, 11) # =3D> [11, 11, 11]
test(10, 3) # =3D> [0, 1, 2, 0, 1, 0, 1, 2, 0, 0]
test(10, -1..1) # =3D> [0, 0, 1, -1, -1, 1, -1, 1, -1, 0]
test(10, 100, 200) # =3D> [126, 148, 183, 140, 188, 175, 115, 157, 136, =20=
179]
begin
test(1, 3, -1)
rescue ArgumentError =3D> error
puts error.message
end # =3D> Arguments not valid for urand
------ code ends