java - Math.random() 与 Random.nextInt(int)

标签 java random

Math.random() * nRandom.nextInt(n) 有什么区别,其中 n 是整数?

最佳答案

这里是 the detailed explanation为什么“Random.nextInt(n)Math.random() * n 更高效且偏差更小”来自 Gili 链接到的 Sun 论坛帖子:

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.

关于java - Math.random() 与 Random.nextInt(int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/738629/

相关文章:

java - 如何在java中为wit.ai音频发送post http请求

Java:在 Linux 中使用包管理器中的 jar 库

java - 从 shell 脚本配置和运行 Ant

php - 使用 PHP 的随机 CSS 类/id 名称

python - Numpy:替换数组中的随机元素

javascript - 我怎样才能将随机变成顺序Javascript?

java - Netbeans:更新按钮事件的文本字段

java - 点击按钮,绘制矩形

Mysql 选择具有多个 where 条件的随机行

php - 中奖机会 PHP 百分比计算