Random.nextint() 和Math.random()的区别

Math.random() uses Random.nextDouble() internally.

Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.

Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.

You will be waiting a very long time rolling dice for this effect to show up.

Math.random() also requires about twice the processing and is subject to synchronization.

                Random rand = new Random();
		long startTime = System.nanoTime() ;
		int i1 = rand.nextInt(1000000000);
		System.out.println(i1);
		long endTime = System.nanoTime();
		System.out.println("Random.nextInt(): " + (endTime - startTime));

		long startTime2 = System.nanoTime();
		int i2 = (int) (java.lang.Math.random() * 1000000000);
		System.out.println(i2);
		long endTime2 = System.nanoTime();
		System.out.println("Math.random():" + (endTime2 - startTime2));

 前者生成的随机数效率高于后者,时间上前者大约是后者50%到80%的时间. 

造成这个原因如下: 
Math.random()是Random.nextDouble()的一个内部方法. 
Random.nextDouble()使用Random.next()两次,均匀的分布范围为0到1 - (2 ^ -53). 
Random.nextInt(n)的使用Random.next()不多于两次, 返回值范围为0到n - 1的分布

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值