I believe you misread those posts. The one you linked essentially says that you shouldn't use random.nextInt() % max
, which is indeed biased; so this approach is very naive. However, if you look at the documentation or source code of Javas nextInt(max)
function, it is more clever than that. Probably unbiased enough for you. Just learn more about the Java API, it has a lot of functionality...
The example discussed in detail generates a single bit in an unbiased way, not an unbiased double random between 0 and 1!
I'm not convinced that Java random generator is substantially biased in the way that you are concernced with. But it certainly is not a high-quality random, because it needs to be fast for most users. If you want a high entropy random, try using the high-quality random sources of your operating system.
Either way, If you want a random number from 0 to 7 using the method linked from your post (which probably is total overkill!), do this:
int bit1 = generateOneBitOfRandom();
int bit2 = generateOneBitOfRandom();
int bit3 = generateOneBitOfRandom();
int zerotoseven = (bit1 << 2) + (bit2 << 1) + bit3;
// Probably at least as good is the proper Java API:
Random random = new Random();
int zerotoseven2 = random.nextInt(8);
Again, most likely, java.util.Random nextInt(8)
will be good enough for you. Unless you are doing cryptography. Then you really should consider just reading a byte from /dev/random
, which may be accessing a hardware entropy pool, if your CPU or mainboard has such features (just hope that one isn't biased / bias cancelled). Which is most likely what Javas SecureRandom
does. Again an example that the Java API is probably much more clever than you think it is.