我正在移植一个简单的 RNG 表单 http://en.wikipedia.org/wiki/Multiply-with-carry去戈朗 但是,不知道是哪里出了问题,我的示例程序的结果是不一致的。
结果:
C = 58 1 78 15 57 28 96 73 47 12 61 47 74 86 91 93
GO= 58 8 18 48 90 72 18 84 54 52 94 80 18 8 2 0
而且我也不明白为什么 t,a 在原始来源中使用 uint64 而不是 uint32。
下面是 C main 和 Go counter 部分:
转到文件:http://play.golang.org/p/YVyIr1bcI8
原 C:
#include <cstdlib>
#include <cstdio>
#include <stdint.h>
#define PHI 0x9e3779b9
static uint32_t Q[4096], c = 362436;
void init_rand(uint32_t x)
{
int i;
Q[0] = x;
Q[1] = x + PHI;
Q[2] = x + PHI + PHI;
for (i = 3; i < 4096; i++)
Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
}
uint32_t rand_cmwc(void)
{
uint64_t t, a = 18782LL;
static uint32_t i = 4095;
uint32_t 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);
}
int main( int argc, char* argv[])
{
init_rand(0);
uint32_t v=0;
for( int i=0; i<16; i++)
{
v = rand_cmwc();
printf( "%d ", (v%100));
}
char input_buf[24]={0};
printf( "\nType a character to exit:", v);
scanf("%s", input_buf);
return 0;
}
最佳答案
嗯?
C 代码在更新时进行 64 位整数运算,保留最上 32 位:
i = (i + 1) & 4095;
t = a * Q[i] + c;
c = (t >> 32);
在 Go 代码中你只使用 32 位整数;当然这是不正确的,因为它永远不会生成正确的高位。
关于c - 我正在将一个简单的 RNG 函数从 C 移植到 Go,结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374954/