如何生成均匀分布随机整数(二)

2014-11-24 07:41:32 · 作者: · 浏览: 1
he correct number of low-order bits would be returned. Linear
* congruential pseudo-random number generators such as the one
* implemented by this class are known to have short periods in the
* sequence of values of their low-order bits. Thus, this special case
* greatly increases the length of the sequence of values returned by
* successive calls to this method if n is a small power of two.
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return the next pseudorandom, uniformly distributed {@code int}
* value between {@code 0} (inclusive) and {@code n} (exclusive)
* from this random number generator's sequence
* @exception IllegalArgumentException if n is not positive
* @since 1.2
*/
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;
}
其中 next(31) 是生成一个31比特的随机整数。判断条件
[java]
while (bits - val + (n-1) < 0)
是怎么来的我没想明白,但是测试了一下结果没有问题。
另外,这个代码中用
[java]
(n & -n) == n
来判断 n 是否是 2 的整数次幂也很巧妙。要是让我来写,肯定写不出这么精彩的实现。
不过,这个代码的运行效率与我写的那个简单的代码基本相当,相比来说我那个代码还要更易读一些。