随机生成数字
Random generation of numbers?
我正在尝试(作为一个笨手笨脚的新手)使用此算法生成随机数
/* 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)。我发现它在这里什么是一个好的随机数生成器的游戏?在评论中有一个人说"我浪费了一个晚上来理解为什么我的代码不能工作:在64位机器上,这段代码生成64位数字!"使用sizeof(unsigned long) * 8
"。我有一个64位系统,但我不明白我要做什么!我使用stdlib肯定更好。
编辑:原来对问题的假设完全错误。你得到全0的原因是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;
}
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 在C++中随机生成 20 个非重复数字
- 为什么我C++得到这个随机的奇怪数字
- C++:创建1000次唯一的随机分布,在任何分布中都没有重复的数字
- 如何编写一个递归函数,以随机的方式混淆从0到6的数字
- 奇怪的数字随机出现在输出中.(C++)
- 生成随机长度的数字字符串
- 随机生成的输出中有多少位数字 1、2、3
- 生成随机字符/数字
- 在随机生成的数组中查找重复的连续数字
- C++ 制作一个随机数字/字母生成器,代码中有问题
- 随机生成数字无法正常工作
- 我可以在不指定数字分布的情况下使用随机生成器吗?
- 随机函数在循环中调用时返回相同的数字!C++
- 保证在随机生成的数字中保证三位数
- 从C 到C#调用INT []显示随机大数字,而不是原始数组成员
- 随机数字双重类型
- c++随机数生成器:如何在每次执行时使数字随机