小编典典

调整XORShift生成器以返回最大范围内的数字

java

我需要在最大范围内生成随机整数。由于 性能至关重要 ,因此我决定使用XORShift生成器,而不是Java的Random类。

long seed = System.nanoTime();
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);

此实现(源)为我提供了一个长整数,但我真正想要的是0到最大值之间的整数。

public int random(int max){ /*...*/}

什么是实现此方法的最有效方法?


阅读 242

收藏
2020-11-16

共1个答案

小编典典

我对您的代码很有趣,并提出了以下建议:

public class XORShiftRandom {

private long last;
private long inc;

public XORShiftRandom() {
    this(System.currentTimeMillis());
}

public XORShiftRandom(long seed) {
    this.last = seed | 1;
    inc = seed;
}

public int nextInt(int max) {
    last ^= (last << 21);
    last ^= (last >>> 35);
    last ^= (last << 4);
    inc += 123456789123456789L;
    int out = (int) ((last+inc) % max);     
    return (out < 0) ? -out : out;
}

}

我做了一个简单的测试,它是大约 倍的速度作为java.util.Random

如果您对它的工作方式很感兴趣,可以阅读以下文章

免责声明:

上面的代码仅用于研究目的,不能代替库存Random或SecureRandom。

2020-11-16