* @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);
}
}
* @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 的 。。。
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);
}
* @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();
}