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#?
Both Java and C++ generate pseudo-random numbers which are either:
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 :-)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With