【问题标题】:Random generation of numbers? [closed]随机生成数字? [关闭]
【发布时间】:2013-04-15 02:23:31
【问题描述】:

我正在尝试(作为一个笨手笨脚的菜鸟)使用这个算法来生成随机数

/* initialize state to random bits */
static unsigned long state[16];
/* init should also reset this to 0 */
static unsigned int index = 0;
/* return 32 bit random number */
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)&0xDA442D20UL);
index = (index + 15)&15;
a = state[index];
state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
return state[index];
}

但它似乎不起作用(结果每次为0)。我在这里找到它What is a good random number generator for a game? 在 cmets 中有一个说“我浪费了一个晚上来理解为什么我的代码不起作用:在 64 位机器上,此代码产生 64 位数字!使用 sizeof(unsigned long) * 8”。我有一个 64 位系统,但我不明白我必须做什么!我使用 stdlib 肯定更好。

【问题讨论】:

  • 作为一般规则,您永远不应该使用您自己不理解的外部来源的代码。即使您复制的摘录有效,它也是向您的程序添加不可预见的错误的可靠方法。
  • 我在评论中询问应该在哪里使用该短语。确保您回来查看原始评论者是否/何时回复。
  • 第二,@Daboyzuk。在 C++ 中,如果您运行您不理解的代码,您就是在让其他人完全访问您机器的裸机。这会让你的机器进入一个充满伤害的世界。
  • 常数应该是(根据原论文):0xDA442D24UL
  • @TommasoFerrari:在您熟练使用第三方代码之前,如何使用标准库?

标签: c++ algorithm random


【解决方案1】:

编辑:对问题的原始假设完全错误。你得到全零的原因是state 没有播种。你需要用“随机”的东西填充state。

此代码有效。请注意,函数seed() 在科学上绝对没有被证明是好的——事实上,我只是边做边编,试图在种子中尽可能多地改变“位”。您应该对“播种随机数”进行一些研究。 (我也尝试只用state[i] = i; 播种,这似乎也很有效,但在前几次迭代中你得到的数字非常相似)。

#include <iostream>
#include <cstdint>

/* initialize state to random bits */
static uint32_t state[16];
/* init should also reset this to 0 */
static unsigned int index = 0;
/* return 32 bit random number */
uint32_t WELLRNG512(void)
{
    uint32_t 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];
}

void seed()
{
    for(size_t i = 0; i < sizeof(state)/sizeof(state[0]); i++)
    {
    state[i] = (i << (24 + (i & 5))) ^ (i << 7) ^ (i << 6) ^ (i >> 2);
    }
}    

int main()
{
    using namespace std;
    seed();
    for(int i = 0; i < 50; i++)
    {
    cout << WELLRNG512() << endl;
    }
    return 0;
}

【讨论】:

  • 非常感谢你真的很善良!
猜你喜欢
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多