Random類產生隨機數


Random 類作為JAVA中用於產生的隨機數 ,new  Random(10)  :10是種子數。
注意:Random 的一個特點是:相同種子數的Random對象,對應相同次數生成的隨機數字是完全相同
 
驗證代碼:
       Random r1 = new Random(10);
 
        Random r2 = new Random(10);
 
        for(int i = 0;i < 4;i++){
 
                 System.out.println(r1.nextInt(5));
        }
System.out.println("++++++++++++++++++++++");
        for(int i = 0;i < 4;i++){
 
                 System.out.println(r2.nextInt(5));
        }
結果:r1 產生的隨機數
3
0
3
0
++++++++++++++++++++++
3       r2產生的隨機數
0
3
0
換成: 
System.out.println(r1. nextDouble(5))System.out.println(r2. nextDouble(5))
結果:
0.7304302967434272
0.2578027905957804
0.059201965811244595
0.24411725056425315
++++++++++++++++++++++
0.7304302967434272
0.2578027905957804
0.059201965811244595
0.24411725056425315
 
分析: 雖然說是隨機數發生器,但是還是按照某種算法一步一步執行下去的,種子數一定算法一樣那么同一時刻的產生的數值當然該一樣了!!
 

* @param seed the initial seed
* @see #setSeed(long)
*/

++++++++++++++++++帶種子數的構造方法+++++++++++++
public Random(long seed) {
if (getClass() == Random.class)
this.seed = new AtomicLong(initialScramble(seed));
else {
// subclass might have overriden setSeed
this.seed = new AtomicLong();
setSeed(seed);
}
}

++++++++++++++netInt方法帶參數的那個源碼++++++++++++

* @since 1.2
*/

public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");

if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);

int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}

可見Random的種子要求 大於0 的 。。。

+++++++++++++++nextDoublef方法實現+++++++++++

public double nextDouble() {
return (((long)(next(26)) << 27) + next(27))
/ (double)(1L << 53);
}

+++++++++++++++nextFloat方法實現+++++++++++++

public float nextFloat() {
return next(24) / ((float)(1 << 24));
}

 

+++++++++++++++++nextInt方法實現:++++++++++
public int nextInt() {
return next(32);
}

 
可見所有的隨機數產生都和一個叫 next方法有關,這個方法是這樣的:

* @since 1.1
*/
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));
}

 
拓展:

Math類中也有一個random方法,該random方法的工作是生成一個[0,1.0)區間的隨機小數。

通過閱讀Math類的源代碼可以發現,Math類中的random方法就是直接調用Random類中的nextDouble方法實現的。

* @see Random#nextDouble()
*/
public static double random() {
Random rnd = randomNumberGenerator;
if (rnd == null) rnd = initRNG();
return rnd.nextDouble();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM