I would like to know the best way to get a pseudorandom float number in a closed interval using the Ruby rand kernel function (please not Random module).
To take an example I will use the closed interval [0.0, 7.7] (both 0.0 and 7.7 included in the interval), but any other float interval should be valid too.
For the interval [0.0, 7.7] the next solution is not valid:
rand * 7.7
Why?
If you call rand without arguments you will get a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. So what is the range of float numbers that the previous solutions can give to us?
rand will return a pseudorandom float number in the range [0.0, 0.9999999…]
0.0 * 7.7
=> 0.0 # Correct!
0.9999999 * 7.7
=> 7.69999923 # Incorrect!
The interval does not match with [0.0, 7.7].
Does anyone know an elegant solution to this problem?
Thank you!
There’s a
Randomclass that can do what you want:(The documentation states the difference between 0.0..7.7 and 0.0…7.7 will be taken in account.)
In the future 1.9.3, you’ll be able to pass a range to
Kernel#randandRandom.rand(you can already do that in the preview version).