Search code examples
javarandommersenne-twister

Is Java's java.util.Random reliable?


I cannot help but notice...after I have started developing my math game (and gave it to beta-testers after constantly tweaking it, and I am still not done!) that my use of java.util.Random and its method nextInt() casted to double may not be the reliable saviour class I was looking for. Is it for generating random numbers for applications like mine? //The point of this app is to make an arithmetic game that is challenging for ALL PEOPLE and lets you solve problems with both integer and floating-point arguments. The highest number my program generates is a 6-digit number, and that is because of some different logic I have used for the Human Calculator (highest level) difficulty, namely for the division problems. I was thinking about using Mersenne twister algorithm, but I think the algorithm used by java.util.Random is something like this: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#next%28int%29 .

Also, I would like to know if it would be recommended that I use something like new java.util.Random(System.currentTimeMillis())


Solution

  • Random's no-arg constructor is already based on the current time (through its cpu nanoTime and not the UTC date) so just creating it will get you a different seed every time. the seeded Random(long) version is (in my experience) mostly used when you want predictable output (some procedural generation routines for computer games, for example, allow the player to specify a random seed)

    if youre very worried about how random your random numbers are, you might want to look at SecureRandom, which is recommended over plain Random for encryption and such. there's a nice explanation of how to use it here and a VERY good explanation of the difference between the two here