随机数/ seed 种子 / System.nanoTime() 的理解 与 使用"/>
Java random随机数/ seed 种子 / System.nanoTime() 的理解 与 使用
伪随机(preundorandom):通过算法产生的随机数都是伪随机!!
只有通过真实的随机事件产生的随机数才是真随机!!比如,通过机器的硬件噪声产生随机数、通过大气噪声产生随机数
Random生成的随机数都是伪随机数!!!
是由可确定的函数(常用线性同余),通过一个种子(常用时钟),产生的伪随机数。这意味着:如果知道了种子,或者已经产生的随机数,都可能获得接下来随机数序列的信息(可预测性)
Random类拥有两个构造方法,用于实现随机数生成器:
- Random( ) 构造一个随机数生成器,种子是 与nanoTime异或后的值。每遍输出的多个序列均不同。随机性更强。
- Random(long seed) 用种子seed构造一个随机数生成器,种子是给定的。每遍输出的多个序列均相同。
源码:
/*** Creates a new random number generator. This constructor sets* the seed of the random number generator to a value very likely* to be distinct from any other invocation of this constructor.*/public Random() {this(seedUniquifier() ^ System.nanoTime());//与System.nanoTime()异或//这里System.nanoTime();并不是以纳秒为单位的系统时间,只用来计算花费多少时间用的。与时间的概念无关。}private static long seedUniquifier() {// L'Ecuyer, "Tables of Linear Congruential Generators of// Different Sizes and Good Lattice Structure", 1999for (;;) {long current = seedUniquifier.get();long next = current * 181783497276652981L;if (seedUniquifierpareAndSet(current, next))return next;}}private static final AtomicLong seedUniquifier= new AtomicLong(8682522807148012L); //种子分配器/*** Creates a new random number generator using a single {@code long} seed.* The seed is the initial value of the internal state of the pseudorandom* number generator which is maintained by method {@link #next}.** <p>The invocation {@code new Random(seed)} is equivalent to:
更多推荐
Java random随机数/ seed 种子 / System.nanoTime() 的理解 与 使用
发布评论