编程语言
首页 > 编程语言> > 为什么java.util.Random使用掩码?

为什么java.util.Random使用掩码?

作者:互联网

简化(即,退出并发)Random.next(int bits)看起来像

protected int next(int bits) {
    seed = (seed * multiplier + addend) & mask;
    return (int) (seed >>> (48 - bits));
}

掩码用于将种子减少到48位.为什么它比仅仅更好

protected int next(int bits) {
    seed = seed * multiplier + addend;
    return (int) (seed >>> (64 - bits));
}

?我已经阅读了很多关于随机数的内容,但是没有理由这样做.

最佳答案:

原因是较低的位往往具有较低的周期(至少在Java使用的算法中)

Wikipedia – Linear Congruential Generator开始:

As shown above, LCG’s do not always use all of the bits in the values they produce. The Java implementation produces 48 bits with each iteration but only returns the 32 most significant bits from these values. This is because the higher-order bits have longer periods than the lower order bits (see below). LCG’s that use this technique produce much better values than those that do not.

编辑:

在进一步阅读之后(方便地,在维基百科上),a,c和m的值必须满足这些条件才能拥有整个期间:

> c和m必须是相对质数
> a-1可被m的所有素因子整除
如果m是4的倍数,则a-1是4的倍数

我能说清楚的唯一一个仍然是#3.需要检查#1和#2,我感觉这些中的一个(或两个)都失败了.

标签:java,masking,random
来源: https://codeday.me/bug/20190515/1109288.html