Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do the "random" generators in different languages (i.e. Java and C++) compare?

Tags:

java

c++

random

Despite the weird title, I wish to ask a legitimate question: which method's generated numbers are more random: Java's Random() class or Math.random(), or C++'s rand()?

I've heard that PHP's rand() is quite bad, i.e. if you map its results you can clearly see a pattern; sadly, I don't know how to draw a map in C++ or Java.

Also, just out of interest, what about C#?

like image 970
Bluefire Avatar asked Feb 04 '13 08:02

Bluefire


3 Answers

Both Java and C++ generate pseudo-random numbers which are either:

  • adequate to the task for anyone who isn't a statistician or cryptographer (a); or
  • woefully inadequate to those two classes of people.

In all honesty, unless you are in one of those classes, pseudo-random number generators are fine.

Java also has SecureRandom which purports to provide crypto-class non-determinism (I can't comment on the veracity of that argument) and C++ now has a much wider variety of random number generation capability than just rand() - see <random> for details.

Specific operating systems may provides sources of entropy for random number generators such as CryptGenRandom under Windows or reading /dev/random under Linux. Alternatively, you could add entropy by using random events such as user input timing.


(a) May actually contain traces of other job types that aren't statistician or cryptographer :-)

like image 60
paxdiablo Avatar answered Oct 23 '22 00:10

paxdiablo


java.util.Random (which is used internally by Math.random()) uses a Linear congruential generator, which is a rather weak RNG, but enough for simple things. For important applications, one should use java.security.SecureRandom instead.

I don't think the C or C++ language specifications proscribe the algorithm to use for rand() but most implementations use a LCG as well. C++11 has added new APIs that yield higher-quality randomness.

like image 30
Michael Borgwardt Avatar answered Oct 23 '22 00:10

Michael Borgwardt


There is a very good document that can be found on the web, done by one of the worldwide experts in random number generators.

Here is the document

The first part of the document is a description of the tests, which you might skip unless your really interested. From page 27, there are the results of the different tests for many generators, including Java, C++, Matlab, Mathematica, Excel, Boost,... (They are described in the text).

It seems that the generator of Java is a bit better, but both are not among the best in the world. The MT19937 from C++11 is already much better.

like image 3
Dr_Sam Avatar answered Oct 23 '22 01:10

Dr_Sam