Search code examples
javarandommasking

Why does java.util.Random use the mask?


Simplified (i.e., leaving concurrency out) Random.next(int bits) looks like

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

where masking gets used to reduce the seed to 48 bits. Why is it better than just

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

? I've read quite a lot about random numbers, but see no reason for this.


Solution

  • It doesn't look like there was a good reason for doing this. Applying the mask is an conservative approach using a proven design. Leaving it out most probably leads to a better generator, however, without knowing the math well, it's a risky step.

    Another small advantage of masking is a speed gain on 8-bit architectures, since it uses 6 bytes instead of 8.