In program development, we often use random numbers. such as digital signatures, data encryption, and some sampling scenarios. However, it is important to note that many development language APIs provide random functions that are not really random, but pseudo-random, and, as a result, are explained at the end of this article.
The random class is available in the JDK for our use
within int rangeSystem.out.println (new random (). Nextint ());//[0,23] System.out.println (new Random (). Nextint (23)) ;//[0.0,1.0] System.out.println (new Random (). nextdouble ());//[0.0,1.0] System.out.println (new Random (). Nextdouble ( );//Generate True or false with equal probabilitySystem.out.println (new Random (). Nextboolean ());
It is important to note that another parameter constructor is provided in the random class random (long Seed)
Let's enter the following code
Random random1 = new random (int i = 0; i < 5; i++) {System.out.println (Random1.nextint ());} Random random2 = new random (int i = 0; i < 5; i++) {System.out.println (Random2.nextint ());} A result is as follows -11504828411434614297156591366825130495960144037--------------11504828411434614297156591366825130495960144037
Some readers may be confused as to why the two random numbers generated by a separate sequence are exactly the same, no doubt! Even if they are generated 10,000 times, the sequence of random numbers they generate is exactly the same! This is also the pseudo-random at the beginning of this article.
In most development languages, the generation of random numbers uses linear and congruential
The mathematical expressions are as follows
X (n+1) = (A * X (n) + C)% m
So, the random number is actually calculated by the formula. when you pass the same seed (seed) when you construct different random classes, you are bound to get the same number sequence!
We observe the core function of the JDK generating random numbers:
protected int next (int BITS) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get (); nextseed = (oldseed * multiplier + addend) & mask; } while (!seed.compareandset (oldseed, nextseed)); return (int) (nextseed >>> (48 - bits)); }
WHERE (Oldseed * multiplier + addend) & Mask is the use of linear and congruential. Only the JDK developer has done some processing. When we use the parameterless constructor, time is used as the seed by default, so even if several random classes are defined, the sequence of random numbers they produce will not be the same. Well, study here today, next time we talk about Apache Commons Lang in the Randomutils class
This article is from the "Codestorm" blog, make sure to keep this source http://codestorm.blog.51cto.com/5917762/1831705
Javase Study-Random number class Java.util.Random class introduction