java随机关系_java> new Random与Math.random()创建随机数的区别与联系

要创建一个随机数,该怎么办?

java中提供了2种方式:Random类和Math.random()

它们有什么区别和联系呢?

Ramdom类

特点

Random类对象是一个伪随机数生成器,使用48bit种子,随机数由线性同余生成器(linear congruential formula)生成。如果2个生成器的种子相同,那么它们会生成完全一样的随机数序列。而默认的种子是系统时间相关的一个数,具体来说是下面seedUniquifier() ^ System.nanoTime(),seedUniquifier()结果是8682522807148012L * 181783497276652981L = 8006678197202707420L。System.nanoTime()是jvm返回的纳秒级的高精度时间。

/**

* 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());

}

private static long seedUniquifier() {

// L'Ecuyer, "Tables of Linear Congruential Generators of

// Different Sizes and Good Lattice Structure", 1999

for (;;) {

long current = seedUniquifier.get();

long next = current * 181783497276652981L;

if (seedUniquifier.compareAndSet(current, next))

return next;

}

}

private static final AtomicLong seedUniquifier

= new AtomicLong(8682522807148012L);

使用方式

要生成随机数,必须得到Random实例,通过nextBoolean(), nextInt(), nextFloat()等来生成对应基本类型的随机数。通过nextXX()传入参数指定范围。

生成的随机数特点

Random实例生成的随机数比较灵活,可以支持多种类型;

示例

生成10个[0,100)的随机数

// java.util.Random

Random r = new Random();

for(int i = 0; i < 10; i++)

int n = r.nextInt(100); // 生成0~100的随机数,不包括100

Math.random方法

特点

Math.random本质上,也是一个Random实例,而且生成的是double类型随机数。不过是创建一个final类型的、种子使用默认种子的Random实例。

public static double random() {

return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();

}

private static final class RandomNumberGeneratorHolder {

static final Random randomNumberGenerator = new Random();

}

使用方式

直接调用Math.random() ,再对所需区间做四则运算

随机数特点

范围[0, 1)

示例

生成10个[5,20)的随机数

for (int i = 0; i < 10; i++) {

int a = (int)(Math.random()*(20-10)) + 5;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值