随机生成器从C到Java的端口?
George Marsaglia写了一个出色的随机数生成器,它非常快速,简单,并且比Mersenne Twister具有更高的周期。下面是带有说明的代码:
我想将CMWC4096代码移植到Java,但它使用几种无符号数据类型,所以我不确定如何正确地执行此操作。以下是完整的 C 代码:
/* choose random initial c<809430660 and */
/* 4096 random 32-bit integers for Q[] */
static unsigned long Q[4096],c=362436;
unsigned long CMWC4096(void) {
unsigned long long t, a=18782LL;
static unsigned long i=4095;
unsigned long x,r=0xfffffffe;
i = (i+1) & 4095;
t = a*Q[i] + c;
c = (t>>32);
x = t + c;
if (x < c) {
x++;
c++;
}
return (Q[i] = r - x);
}
任何人都可以将其移植到Java吗?当您只有可用的签名号码时,这是如何工作的?
编辑:感谢大家的快速回答!对于前 1 亿个数字,此 java 代码似乎产生与 C 代码相同的结果。它比Java的java.util.Random快3倍。
public class ComplimentaryMultiplyWithCarryRandom {
/**
* Choose 4096 random 32-bit integers
*/
private long[] Q;
/**
* choose random initial c<809430660
*/
private long c = 362436;
private int i;
public ComplimentaryMultiplyWithCarryRandom() {
Random r = new Random(1);
Q = new long[4096];
// TODO initialize with real random 32bit values
for (int i = 0; i < 4096; ++i) {
long v = r.nextInt();
v -= Integer.MIN_VALUE;
Q[i] = v;
}
i = 4095;
}
int next() {
i = (i + 1) & 4095;
long t = 18782 * Q[i] + c;
c = t >>> 32;
long x = (t + c) & 0xffffffffL;
if (x < c) {
++x;
++c;
}
long v = 0xfffffffeL - x;
Q[i] = v;
return (int) v;
}
}