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

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

问题描述

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

解决方案

这里是 来自 Sun 论坛的Random.nextInt(n)Math.random() * n"更有效且偏差更少的详细解释Gili 链接到的帖子:

<块引用>

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

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

Random.nextInt(n) 使用 Random.next() 平均少于两次 - 它使用它一次,如果获得的值高于 MAX_INT 以下的 n 的最高倍数,则再次尝试,否则返回模数n(这可以防止高于 MAX_INT 下的 n 的最高倍数的值扭曲分布),因此返回一个在 0 到 n-1 范围内均匀分布的值.

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

按 6 缩放不会改变可能值的数量,并且转换为 int 然后将这些值强制放入六个桶"(0、1、2、3、4、5)之一,每个桶对应于包含可能值的 1501199875790165 或 1501199875790166 的范围(因为 6 不是 2^53 的除数).这意味着对于足够数量的骰子(或具有足够多边的骰子),骰子将显示自己偏向较大的桶.

您将等待很长时间掷骰子才能显示此效果.

Math.random() 也需要大约两倍的处理,并且需要同步.

What is the difference between Math.random() * n and Random.nextInt(n) where n is an integer?

解决方案

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() 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.

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

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