How do you create pseudo random numbers sequentially in c/c++?
srand(time(NULL));
for (it=hand.begin(); it < hand.end(); it++)
(*it) = rand() % 13 + 1;
This code does not work to create many random numbers at a time. Is there a way to do it that isn't as开发者_如何学C complex as Mersennes and isn't operating system dependent?
PRNGs don't create many PRNs at once. Each output is dependent on the previous output, PRNGs are highly stateful.
Try:
srand(time(NULL)); // once at the start of the program
for( int i = 0; i < N; ++i )
r[i] = rand();
Even APIs that return an entire block of output in a single function call, have just moved that loop inside the function.
Call srand
just once, at the start of your program. Then call rand()
(not srand(rand())
) to generate each random number.
Boost.Random has lots of good random number generators which are easy to use.
George Marsaglia posted a Multiply With Carry PRNG some time ago in sci.math.
I cannot say how good it is or how well it behaves, but you might want to give it a try.
It should be OS and platform independent.
"please make sure you answer the question" OK
for (int i=n1; i < n2; ++i)
{
int k;
do k = rand(); while (i !=k);
// k is a sequential pseudo random number
}
There may be issues with efficiency...
精彩评论