调整XORShift发生器以返回最大值 [英] Adjusting XORShift generator to return a number within a maximum
问题描述
我需要在最大值内生成随机整数。由于性能至关重要,我决定使用XORShift生成器而不是Java的Random类。
I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java's Random class.
long seed = System.nanoTime();
seed ^= (seed << 21);
seed ^= (seed >>> 35);
seed ^= (seed << 4);
此实现 (source) 给我一个长整数,但我真正想要的是0到最大值之间的整数。
This implementation (source) gives me a long integer, but what I really want is an integer between 0 and a maximum.
public int random(int max){ /*...*/}
实现此方法的最有效方法是什么?
What it is the most efficient way to implement this method?
推荐答案
我对你的代码感兴趣并想出了这个:
I had some fun with your code and came up with this:
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
I did a simple test and it is about Four times as fast as the java.util.Random
如果你如果它有用,你可以阅读这个论文:
If you are intrested in how it works you can read this paper:
免责声明:
上述代码仅用于研究,而不是用于
替换股票Random或SecureRandom。
The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.
这篇关于调整XORShift发生器以返回最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!