1

我看过很多关于 WELLRNG512 的帖子。假设我已经得出结论,对于一个 roguelike 地牢爬行者来说,这将是一个比 Mersenne Twister 更好的选择。我试图让这段代码生成随机数并且行为很像 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()?

PS:我是学生,绝对不是数学家,所以如果您要使用任何象形文字来解释公式等,请详细解释您的答案。

4

1 回答 1

1

代码有一些问题。最重要的一点:您永远不会调用随机数生成器。这一行在这里:

   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;
}

那应该可以解决您的问题。

于 2014-02-02T21:38:35.807 回答