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);
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以将其移植到Java吗?当您只有签名号码时,这是如何工作的?
编辑:谢谢大家快速解答!对于前1亿个数字,这个java代码似乎产生与C代码相同的结果.它比Java的java.util.Random快3倍.
public class ComplimentaryMultiplyWithCarryRandom { …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我在哪里以及究竟做错了什么?将数据向左旋转时,我得到了意想不到的值.有什么办法解决这个问题?
public class RotateExample {
public static byte rotateRight(byte bits, int shift) {
return (byte)((bits >>> shift) | (bits << (8 - shift)));
}
public static byte rotateLeft(byte bits, int shift) {
return (byte)((bits << shift) | (bits >>> (8 - shift)));
}
public static void main(String[] args) {
//test 1 failed
byte a = (byte)1;
byte b = rotateRight(a,1);
byte c = rotateLeft(b,1);
System.out.println(a+" "+b+" "+c);
//test 2 passed
a = (byte)1;
b = rotateRight(a,2);
c = rotateLeft(b,2);
System.out.println(a+" …Run Code Online (Sandbox Code Playgroud)