5 ms·
>The code above is certainly an inelegant solution, since it is, in theory, at least, a potentially infinite loop. As far as I know, it is the only solution fo
by mistercow 13y ago
>The code above is certainly an inelegant solution, since it is, in theory, at least, a potentially infinite loop.
As far as I know, it is the only solution for generating unbiased random numbers in a range that does not divide the native range of the PRNG you're using.
What I don't understand is why they're working in decimal in the first place. The obvious solution is to generate a random integer in the range [0, 2^53) (which does not require an unbounded-time loop, since 2^53 divides 2^64) and then divide by 2^53. I am open to the possibility that there's some quirk of floating point arithmetic that means that won't work [edit: less so now that I see it's how Java implements it¹], but I can hardly imagine that it's worse than this crazy business of generating 16 decimal digits because, hey, log₁₀(2^53) is pretty close to 16.
¹http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextDouble() http://docs.oracle.com/javase/7/docs/api/java/util/Random.ht...