Several questions have recently been asking about random. I see a lot of answers in those questions using the date not as a seed but as the random number that is then modulo'ed.
Seen in Java:
System.currentTimeMillis()%N
System.nanoTime()%N
Seen in JavaScript:
new Date%N
Doing so is randomly unfair for two reasons:
- the code will often return the same values if run in quick successions, also if the time ticks during two runs, you know you'll get the next value. You may be surprised by the first run, making it random, but not by the next ones.
- the the modulo bias is then alive and well.
What are the views of the community on this topic?
java.util.Random
, and Javascript hasMath.random()
. Relevant. \$\endgroup\$System.nanoTime()
returns along
, there is definitely an upper bound to along
. I don't know how JS represents its numbers in intern, is it a fixed-bits long, double? If it's either, then there is a modulo bias because if it's a long, then see the link I provided or else the lack of precision from certain values make it discontinued, meaning not uniform. \$\endgroup\$System.currentTimeMillis()
used to give increments by 15 or 16, so you it returned the same value for 15 actual milliseconds. That was fixed with Java 5 or 6 I don't remember, but that was disturbing at the time ;) \$\endgroup\$