Java random随机数/ seed 种子 / System.nanoTime() 的理解 与 使用

编程入门 行业动态 更新时间:2024-10-28 06:31:27

Java random<a href=https://www.elefans.com/category/jswz/34/1766016.html style=随机数/ seed 种子 / System.nanoTime() 的理解 与 使用"/>

Java random随机数/ seed 种子 / System.nanoTime() 的理解 与 使用

伪随机(preundorandom):通过算法产生的随机数都是伪随机!!

只有通过真实的随机事件产生的随机数才是真随机!!比如,通过机器的硬件噪声产生随机数、通过大气噪声产生随机数

Random生成的随机数都是伪随机数!!!

是由可确定的函数(常用线性同余),通过一个种子(常用时钟),产生的伪随机数。这意味着:如果知道了种子,或者已经产生的随机数,都可能获得接下来随机数序列的信息(可预测性)

Random类拥有两个构造方法,用于实现随机数生成器:

  1. Random( ) 构造一个随机数生成器,种子是 与nanoTime异或后的值。每遍输出的多个序列均不同。随机性更强。
  2. 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() 的理解 与 使用

本文发布于:2024-02-12 17:13:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1688690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   种子   Java   random   nanoTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!