我看过很多关于 WELLRNG512 的帖子。据推测,我已经得出结论,对于 roguelike 地牢爬行者来说,这将是比 Mersenne Twister 更好的选择。我正在尝试获取 this一段生成随机数的代码,其行为与 rand() 非常相似。
使用的代码:
static unsigned long state[16];
static unsigned int index = 0;
int main (void) {
int i;
for (i = 0; i < 16; i++) {
index = i;
printf("random: %lu\n", WELLRNG512());
}
return 0;
}
unsigned long WELLRNG512 (void) {
unsigned long a, b, c, d;
a = state[index];
c = state[(index+13)&15];
b = a^c^(a<<16)^(c<<15);
c = state[(index+9)&15];
c ^= (c>>11);
a = state[index] = b^c;
d = a^((a<<5)&0xDA442D24UL);
index = (index + 15)&15;
a = state[index];
state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
return state[index];
}
预期结果:
random: 231544
random: 542312
random: 588690
(...etc...)
获得的结果:
random: 4195755
random: 4195755
random: 4195755
(...etc...)
有没有人知道我如何才能成功地使这段代码的行为类似于 rand()?
P.S.:我是一名学生,绝对不是数学家,所以如果您要使用任何一种象形文字来解释公式等,请详细解释您的答案。
最佳答案
代码有些问题。最重要的一点:您永远不会调用随机数生成器。这行在这里:
printf("random: %lu\n", WELLRNG512);
打印 WELLRNG512 函数的地址。它不会调用它。要解决此问题,请尝试:
printf("random: %lu\n", WELLRNG512());
第二:状态数组必须用随机数据填充。只是为了测试,我根据 rand() 函数把一些东西放在一起。这可能是也可能不是一种为状态数组提供种子的聪明方法,但它足以从您的函数中获取一些随机数据。
/* seed the state array */
for (i = 0; i < 16; i++)
state[i] = rand()^(rand()<<16)^(rand()<<31);
最后一件事:函数 WELLRNG512 递增索引变量本身。在 main 中的测试循环中不需要这样做。
我完整的主要功能如下所示:
int main (void) {
int i;
/* seed */
for (i = 0; i < 16; i++)
state[i] = rand()^(rand()<<16)^(rand()<<31);
for (i = 0; i < 16; i++) {
printf("random: %lu\n", WELLRNG512());
}
return 0;
}
这应该可以解决您的问题。
关于c - WELLRNG512 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515936/