我认为Java随机函数有一些bug ......
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
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;
}
如果我认为正确,nextInt(n)函数返回范围[0,n]中的均匀分布(所有整数具有相同的概率) (n是正数,因为如果它是&lt; = 0那么它将抛出异常。)
...
我听说nextInt(n)函数的原因并不是简单地修改位变量,如下所示
next(31) % n
是因为n可能小于next(31)并且它会扭曲均匀分布。 (链接:Why 2^31 is not divisible by n?)
如果这就是我认为存在问题的原因..
原始代码检查条件
位 - val +(n-1)&lt; 0
但是位总是大于val(val =位%n,n是正整数) 比特 - val&gt; 0
且n - 1> = 0,因为n是正整数。
所以..
bit - val +(n - 1)将始终大于0 所以...循环永远不会运行两次..我是对的吗?