【发布时间】:2021-01-06 00:09:48
【问题描述】:
您好,我编写了一个 C++ 程序,它使用 rand() 函数处理随机数,结果很奇怪。实际代码中还有很多内容,但代码的基本思想类似于:
int main()
{
srand(time(NULL));
priority_queue<long long int> pQueueInts;
const int TRIALS = 1000000;
for (int i = 0; i < TRIALS; i++)
{
long long int holder = randomNumber();
pQueueInts.push(holder);
}
cout << pQueueInts.top();
for (int i = 0; i < TRIALS / 2; i++)
pQueueInts.pop();
cout << pQueueInts.top();
for (int i = 0; i < (TRIALS / 2) - 1; i++)
pQueueInts.pop();
cout << pQueueInts.top();
}
long long int randomNumber()
{
bool found = false;
long long int counter = 0;
while (found == false)
{
int roll = rand() % 500;
if (roll == 1)
{
roll = rand() % 500;
if (roll == 2)
found = true;
}
counter++;
}
found = false;
while (found == false)
{
int roll = rand() % 100;
if (roll == 3)
{
roll = rand() % 250;
if (roll == 4)
found = true;
}
counter++;
}
found = false;
while (found == false)
{
int roll = rand() % 530;
if (roll == 5)
{
roll = rand() % 400;
if (roll == 6)
found = true;
}
counter++;
}
return counter / 3;
}
它运行并执行得很好,但是如果我说进行 1M 次试验并从中找到最大的计数器结果,然后我退出程序并再次运行它,但是经过 1000 次试验,您会期望该样本中最大的计数器更小比 1M 试验,但它的数字完全相同。如果我随后将样本更改为 10M,我可能会得到一个新的高值,再次关闭程序并重新运行 1000 次试验,我可能会从 10M 样本中得到新的高值,因为它恰好是 1000 样本的高值,这非常不可能,尤其是使用我的实际代码,结果差异更大。
我认为 rand() 函数或我不理解的 c++ 语言发生了一些问题,这是造成这种情况的原因吗?感谢您的任何启发。
【问题讨论】:
-
这是一个奇怪的
randomNumber函数。你能解释一下它应该做什么,因为我不介意打赌问题出在那个函数上。 -
说出您看到的数字可能会有所帮助。是不是每次运行程序都完全一样。
-
警告:使用
rand()can be highly problematic,我们强烈建议您使用合适的random number generator facility in the Standard Library,以产生高质量的随机值。您使用time(NULL)作为随机数种子意味着如果在同一秒内运行,这将产生相同的结果,并且在许多平台上rand()是barely random at all。
标签: c++ loops random statistics srand