Math.random()与Random.nextInt(int) [英] Math.random() versus Random.nextInt(int)

查看:139
本文介绍了Math.random()与Random.nextInt(int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Math.random()* n Random.nextInt(n)其中 n 是一个整数?

推荐答案

这是详细解释为什么 Random.nextInt(n)比Gili链接的Sun论坛帖子中的 Math.random()* n 更高效且更少偏见:

Here is the detailed explanation of why "Random.nextInt(n) is both more efficient and less biased than Math.random() * n" from the Sun forums post that Gili linked to:


Math.random()在内部使用Random.nextDouble()。

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

Random.nextDouble()使用Random.next()两次生成一个双尾,在其尾数中具有近似均匀分布的位,因此它均匀分布在0范围内到1-(2 ^ -53)。

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)使用Random.next()平均不到两次 - 它使用一次,如果获得的值高于MAX_INT以下的最高倍数,它再次尝试,否则返回模数n的值(这可以防止高于MAX_INT的最高倍数的值偏离分布),因此返回一个均匀分布的值范围0到n-1。

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.

在缩放6之前,Math.random()的输出是从均匀分布中提取的2 ^ 53个可能值之一。

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

按6缩放不会改变可能的值的数量,并且转换为int然后将这些值强制为六个桶中的一个(0,1,2) ,3,4,5),每个桶对应于包含可能值的1501199875790165或1501199875790166的范围(因为6不是2 ^ 53的管理员)。这意味着对于足够数量的骰子卷(或具有足够大的边数的骰子),骰子将显示出偏向更大的骰子。

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()也需要大约两倍的处理并且需要同步。

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

这篇关于Math.random()与Random.nextInt(int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆