问题描述
此功能来自。它返回一个伪随机 int
,均匀分布在 0
和给定的 n $ c $之间C>。不幸的是我没有得到它。
This function is from java.util.Random
. It returns a pseudorandom int
uniformly distributed between 0
and the given n
. Unfortunately I did not get it.
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
我的问题是:
- 为什么它会处理
n
特别是2的幂的情况?这仅仅是为了表现吗? - 为什么它会拒绝
位数 - val +(n-1)< 0
?
- Why does it treat the case where
n
is a power of two specially ? Is it just for performance ? - Why doest it reject numbers that
bits - val + (n-1) < 0
?
推荐答案
next
生成随机位。
-
当
n时
是2的幂,该范围内的随机整数可以通过生成随机位来生成(我假设始终生成31并抛出一些是为了再现性)。这个代码路径更简单,我想这是一个更常用的情况,所以值得为这种情况制作一个特殊的快速路径。
When
n
is a power of 2, a random integer in that range can be generated just by generating random bits (I assume that always generating 31 and throwing some away is for reproducibility). This code path is simpler and I guess it's a more commonly used case so it's worth making a special "fast path" for this case.
当<$ c时$ c> n 不是2的幂,它会抛弃范围顶部的数字,以便随机数均匀分布。例如。想象我们有 n = 3
,想象我们使用3位而不是31位。所以位
是一个0到7之间随机生成的数字。如何在那里生成一个公平的随机数?答案:如果位
为6或7,我们将其扔掉并生成一个新的。
When n
isn't a power of 2, it throws away numbers at the "top" of the range so that the random number is evenly distributed. E.g. imagine we had n=3
, and imagine we were using 3 bits rather than 31 bits. So bits
is a randomly generated number between 0 and 7. How can you generate a fair random number there? Answer: if bits
is 6 or 7, we throw it away and generate a new one.
这篇关于java.util.Random.nextInt的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!