3 ms·
> I'd do Math.random(min,max) But then you'd need a different way to do random non-integers. Randomness does not naturally produce an integer result. The 0-1
by quesera 4y ago
> I'd do Math.random(min,max)
But then you'd need a different way to do random non-integers.
Randomness does not naturally produce an integer result. The 0-1 range with precision determined by the architecture is actually the simplest and most logical and flexible way to do it. [EDIT: floats are never simple, see below!]
Some languages offer convenience functions on top of the low level random number generator. I don't know what's available in JavaScript.
E.g. in ruby:
irb(main):001:0> rand
=> 0.5562701792527804
irb(main):002:0> rand(100)
=> 44
irb(main):003:0> rand(44..203)
=> 188
...but of course, I could go on all day long about how pleasant Ruby is to work with. :)
- deathanatos 4y ago> Randomness does not naturally produce an integer result. The 0-1 range with precision determined by the architecture is actually the simplest and most logical and flexible way to do it. The most trivial way, I would think, would be to interpret a stream of bits would be as an unsigned integer. E.g., a u32 is just "take 32 bits of random data from your RNG, and cast." That's certainly far more natural than trying to build an IEEE double from [0, 1) with a uniform distribution. I'm actually not sure how you'd do that without doing something like starting with a random u32 and dividing by (U32_MAX + 1). Like maybe you can shove the RNG output into the mantissa, but it is not at all obvious to me about the correctness of that.
- quesera 4y agoMmm, great points. At least for range [0,MAXINT], it is simple to fill the bitspace for an integer. Range [0,limit) requires slightly more-awkward division. The problem of uniformity across the range in a populated float is critical -- as you point out, IEEE float layouts are not simple. I would guess that the "float" result is constructed as a fixed-point decimal in the same way you would an integer (sprinkle the RNG bits over the storage bitspace), but returned as float (via cast or math) to match the language type system.