简介
- 随机数字生成器
-
源码
public class Random implements java.io.Serializable {static final long serialVersionUID = 3905348978240129619L;// 此处是一个 原子类 AtomicLong 种子private final AtomicLong seed;// 乘数private static final long multiplier = 0x5DEECE66DL;// 加数private static final long addend = 0xBL;//private static final long mask = (1L << 48) - 1;private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)// IllegalArgumentException消息static final String BadBound = "bound must be positive";static final String BadRange = "bound must be greater than origin";static final String BadSize = "size must be non-negative";// 无参构造器 调用另一个有参构造器public Random() {this(seedUniquifier() ^ System.nanoTime());}// 种子统一符方法private static long seedUniquifier() {for (;;) {long current = seedUniquifier.get();long next = current * 181783497276652981L;if (seedUniquifier.compareAndSet(current, next))return next;}}// 种子统一数据private static final AtomicLong seedUniquifier= new AtomicLong(8682522807148012L);// 参数为种子长度的构造方法public Random(long seed) {if (getClass() == Random.class)this.seed = new AtomicLong(initialScramble(seed));else {this.seed = new AtomicLong();setSeed(seed);}}private static long initialScramble(long seed) {return (seed ^ multiplier) & mask;}// 设置此随机数生成器的使用单个种子long的种子。// 总承包setSeed是,它改变了这个随机数生成器对象的状态,// 从而,如果它刚刚与参数创建是完全相同的状态seed的种子。// 该方法setSeed由类实现Random通过原子地更新所述种子// (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1) 并清除haveNextNextGaussian由已使用标记synchronized public void setSeed(long seed) {this.seed.set(initialScramble(seed));haveNextNextGaussian = false;}// 产生一个伪随机数。 子类应覆盖这一点,因为这是使用的所有其他方法。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));}// 生成随机字节并将它们放置到用户提供的字节数组。 产生的随机字节数等于字节数组的长度public void nextBytes(byte[] bytes) {for (int i = 0, len = bytes.length; i < len; )for (int rnd = nextInt(),n = Math.min(len - i, Integer.SIZE/Byte.SIZE);n-- > 0; rnd >>= Byte.SIZE)bytes[i++] = (byte)rnd;}// nextLong的形式使用通过LongStream Spliterators。// 如果原产地是大于约束,作为nextLong的无限形式,否则为界形式final long internalNextLong(long origin, long bound) {long r = nextLong();if (origin < bound) {long n = bound - origin, m = n - 1;if ((n & m) == 0L) // power of twor = (r & m) + origin;else if (n > 0L) { // reject over-represented candidatesfor (long u = r >>> 1; // ensure nonnegativeu + m - (r = u % n) < 0L; // rejection checku = nextLong() >>> 1) // retry;r += origin;}else { // range not representable as longwhile (r < origin || r >= bound)r = nextLong();}}return r;}// 返回伪随机值final int internalNextInt(int origin, int bound) {if (origin < bound) {int n = bound - origin;if (n > 0) {return nextInt(n) + origin;}else { // range not representable as intint r;do {r = nextInt();} while (r < origin || r >= bound);return r;}}else {return nextInt();}}// 返回伪随机值final double internalNextDouble(double origin, double bound) {double r = nextDouble();if (origin < bound) {r = r * (bound - origin) + origin;if (r >= bound) // correct for roundingr = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);}return r;}// 无参数的nextInt方法public int nextInt() {return next(32);}// 带有参数的 nextInt 方法,参数为界限public int nextInt(int bound) {if (bound <= 0)throw new IllegalArgumentException(BadBound);int r = next(31);int m = bound - 1;if ((bound & m) == 0) // i.e., bound is a power of 2r = (int)((bound * (long)r) >> 31);else {for (int u = r;u - (r = u % bound) + m < 0;u = next(31));}return r;}// 返回下一个伪,均匀分布的long从该随机数生成器的序列值。// 总承包nextLong是一个long值伪随机地生成并返回public long nextLong() {// it's okay that the bottom word remains signed.return ((long)(next(32)) << 32) + next(32);}// 返回均匀分布的boolean值public boolean nextBoolean() {return next(1) != 0;}// 返回均匀分布的 ,在[0.0,1.0)之间的float数public float nextFloat() {return next(24) / ((float)(1 << 24));}// 返回均匀分布的 ,在[0.0,1.0)之间的double数public double nextDouble() {return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;}private double nextNextGaussian;private boolean haveNextNextGaussian = false;// 返回下一个伪高斯(“正常”)分布的double用平均值0.0和标准偏差1.0从该随机数生成器的序列。synchronized public double nextGaussian() {// See Knuth, ACP, Section 3.4.1 Algorithm C.if (haveNextNextGaussian) {haveNextNextGaussian = false;return nextNextGaussian;} else {double v1, v2, s;do {v1 = 2 * nextDouble() - 1; // between -1 and 1v2 = 2 * nextDouble() - 1; // between -1 and 1s = v1 * v1 + v2 * v2;} while (s >= 1 || s == 0);double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);nextNextGaussian = v2 * multiplier;haveNextNextGaussian = true;return v1 * multiplier;}}// 返回产生所述给定流streamSize伪随机数int值。// 伪随机int ,如果是在调用该方法的结果生成的值nextInt()public IntStream ints(long streamSize) {if (streamSize < 0L)throw new IllegalArgumentException(BadSize);return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, streamSize, Integer.MAX_VALUE, 0),false);}public IntStream ints() {return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),false);}public IntStream ints(long streamSize, int randomNumberOrigin,int randomNumberBound) {if (streamSize < 0L)throw new IllegalArgumentException(BadSize);if (randomNumberOrigin >= randomNumberBound)throw new IllegalArgumentException(BadRange);return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound),false);}public IntStream ints(int randomNumberOrigin, int randomNumberBound) {if (randomNumberOrigin >= randomNumberBound)throw new IllegalArgumentException(BadRange);return StreamSupport.intStream(new RandomIntsSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),false);}// 返回生产给定流streamSize伪随机数long值public LongStream longs(long streamSize) {if (streamSize < 0L)throw new IllegalArgumentException(BadSize);return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, streamSize, Long.MAX_VALUE, 0L),false);}public LongStream longs() {return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),false);}public LongStream longs(long streamSize, long randomNumberOrigin,long randomNumberBound) {if (streamSize < 0L)throw new IllegalArgumentException(BadSize);if (randomNumberOrigin >= randomNumberBound)throw new IllegalArgumentException(BadRange);return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, streamSize, randomNumberOrigin, randomNumberBound),false);}public LongStream longs(long randomNumberOrigin, long randomNumberBound) {if (randomNumberOrigin >= randomNumberBound)throw new IllegalArgumentException(BadRange);return StreamSupport.longStream(new RandomLongsSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),false);}public DoubleStream doubles(long streamSize) {if (streamSize < 0L)throw new IllegalArgumentException(BadSize);return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, streamSize, Double.MAX_VALUE, 0.0),false);}public DoubleStream doubles() {return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),false);}public DoubleStream doubles() {return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),false);}public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {if (!(randomNumberOrigin < randomNumberBound))throw new IllegalArgumentException(BadRange);return StreamSupport.doubleStream(new RandomDoublesSpliterator(this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),false);}// 静态内部类 分流器static final class RandomIntsSpliterator implements Spliterator.OfInt {final Random rng;long index;final long fence;final int origin;final int bound;RandomIntsSpliterator(Random rng, long index, long fence,int origin, int bound) {this.rng = rng; this.index = index; this.fence = fence;this.origin = origin; this.bound = bound;}public RandomIntsSpliterator trySplit() {long i = index, m = (i + fence) >>> 1;return (m <= i) ? null :new RandomIntsSpliterator(rng, i, index = m, origin, bound);}public long estimateSize() {return fence - index;}public int characteristics() {return (Spliterator.SIZED | Spliterator.SUBSIZED |Spliterator.NONNULL | Spliterator.IMMUTABLE);}public boolean tryAdvance(IntConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {consumer.accept(rng.internalNextInt(origin, bound));index = i + 1;return true;}return false;}public void forEachRemaining(IntConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {index = f;Random r = rng;int o = origin, b = bound;do {consumer.accept(r.internalNextInt(o, b));} while (++i < f);}}}// 分词器static final class RandomLongsSpliterator implements Spliterator.OfLong {final Random rng;long index;final long fence;final long origin;final long bound;RandomLongsSpliterator(Random rng, long index, long fence,long origin, long bound) {this.rng = rng; this.index = index; this.fence = fence;this.origin = origin; this.bound = bound;}public RandomLongsSpliterator trySplit() {long i = index, m = (i + fence) >>> 1;return (m <= i) ? null :new RandomLongsSpliterator(rng, i, index = m, origin, bound);}public long estimateSize() {return fence - index;}public int characteristics() {return (Spliterator.SIZED | Spliterator.SUBSIZED |Spliterator.NONNULL | Spliterator.IMMUTABLE);}public boolean tryAdvance(LongConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {consumer.accept(rng.internalNextLong(origin, bound));index = i + 1;return true;}return false;}public void forEachRemaining(LongConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {index = f;Random r = rng;long o = origin, b = bound;do {consumer.accept(r.internalNextLong(o, b));} while (++i < f);}}}// 分词器static final class RandomLongsSpliterator implements Spliterator.OfLong {final Random rng;long index;final long fence;final long origin;final long bound;RandomLongsSpliterator(Random rng, long index, long fence,long origin, long bound) {this.rng = rng; this.index = index; this.fence = fence;this.origin = origin; this.bound = bound;}public RandomLongsSpliterator trySplit() {long i = index, m = (i + fence) >>> 1;return (m <= i) ? null :new RandomLongsSpliterator(rng, i, index = m, origin, bound);}public long estimateSize() {return fence - index;}public int characteristics() {return (Spliterator.SIZED | Spliterator.SUBSIZED |Spliterator.NONNULL | Spliterator.IMMUTABLE);}public boolean tryAdvance(LongConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {consumer.accept(rng.internalNextLong(origin, bound));index = i + 1;return true;}return false;}public void forEachRemaining(LongConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {index = f;Random r = rng;long o = origin, b = bound;do {consumer.accept(r.internalNextLong(o, b));} while (++i < f);}}}//static final class RandomDoublesSpliterator implements Spliterator.OfDouble {final Random rng;long index;final long fence;final double origin;final double bound;RandomDoublesSpliterator(Random rng, long index, long fence,double origin, double bound) {this.rng = rng; this.index = index; this.fence = fence;this.origin = origin; this.bound = bound;}public RandomDoublesSpliterator trySplit() {long i = index, m = (i + fence) >>> 1;return (m <= i) ? null :new RandomDoublesSpliterator(rng, i, index = m, origin, bound);}public long estimateSize() {return fence - index;}public int characteristics() {return (Spliterator.SIZED | Spliterator.SUBSIZED |Spliterator.NONNULL | Spliterator.IMMUTABLE);}public boolean tryAdvance(DoubleConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {consumer.accept(rng.internalNextDouble(origin, bound));index = i + 1;return true;}return false;}public void forEachRemaining(DoubleConsumer consumer) {if (consumer == null) throw new NullPointerException();long i = index, f = fence;if (i < f) {index = f;Random r = rng;double o = origin, b = bound;do {consumer.accept(r.internalNextDouble(o, b));} while (++i < f);}}}private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("seed", Long.TYPE),new ObjectStreamField("nextNextGaussian", Double.TYPE),new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)};private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {ObjectInputStream.GetField fields = s.readFields();long seedVal = fields.get("seed", -1L);if (seedVal < 0)throw new java.io.StreamCorruptedException("Random: invalid seed");resetSeed(seedVal);nextNextGaussian = fields.get("nextNextGaussian", 0.0);haveNextNextGaussian = fields.get("haveNextNextGaussian", false);}synchronized private void writeObject(ObjectOutputStream s)throws IOException {// set the values of the Serializable fieldsObjectOutputStream.PutField fields = s.putFields();// The seed is serialized as a long for historical reasons.fields.put("seed", seed.get());fields.put("nextNextGaussian", nextNextGaussian);fields.put("haveNextNextGaussian", haveNextNextGaussian);// save thems.writeFields();}private static final Unsafe unsafe = Unsafe.getUnsafe();private static final long seedOffset;static {try {seedOffset = unsafe.objectFieldOffset(Random.class.getDeclaredField("seed"));} catch (Exception ex) { throw new Error(ex); }}private void resetSeed(long seedVal) {unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));}}
伪随机数
public class RandomTest { public static void main(String[] args) { //只要两个Random对象的种子相同,而且方法的调用顺序也相同,产生的随机数相同 //Random产生的数字并不是真正随机的,而是一种伪随机 Random r1 = new Random(16); System.out.println("第一个种子为16的Random对象"); System.out.println("r1.nextBoolean() = " + r1.nextBoolean()); System.out.println("r1.nextInt() = " + r1.nextInt()); System.out.println("r1.nextDouble() = " + r1.nextDouble()); System.out.println("r1.nextGaussian() = " + r1.nextGaussian()); System.out.println("-------------------------------------------------------"); } } 多次的执行结果如下 ```java 第一个种子为16的Random对象 r1.nextBoolean() = true r1.nextInt() = -2031839431 r1.nextDouble() = 0.527826082540034 r1.nextGaussian() = 0.014363412537037566
```
