【发布时间】:2011-08-06 23:44:03
【问题描述】:
srand(time(NULL));
for (it=hand.begin(); it < hand.end(); it++)
(*it) = rand() % 13 + 1;
此代码不能一次创建多个随机数。 有没有办法做到不像 Mersennes 那样复杂并且不依赖于操作系统?
【问题讨论】:
srand(time(NULL));
for (it=hand.begin(); it < hand.end(); it++)
(*it) = rand() % 13 + 1;
此代码不能一次创建多个随机数。 有没有办法做到不像 Mersennes 那样复杂并且不依赖于操作系统?
【问题讨论】:
PRNG 不会一次创建多个 PRN。每个输出都依赖于前一个输出,PRNG 是高度有状态的。
试试:
srand(time(NULL)); // once at the start of the program
for( int i = 0; i < N; ++i )
r[i] = rand();
即使是在单个函数调用中返回整个输出块的 API,也只是将该循环移到了函数中。
【讨论】:
在程序开始时只调用一次srand。然后调用rand()(不是srand(rand()))生成每个随机数。
【讨论】:
Boost.Random 有很多很好用的随机数生成器。
【讨论】:
George Marsaglia 不久前在 sci.math 上发布了 Multiply With Carry PRNG。
我不能说它有多好或表现如何,但你可能想试一试。
它应该独立于操作系统和平台。
【讨论】:
“请确保你回答了这个问题” 好的
for (int i=n1; i < n2; ++i)
{
int k;
do k = rand(); while (i !=k);
// k is a sequential pseudo random number
}
效率可能存在问题...
【讨论】: