Pergunta

C++ question here, using Code::Blocks. I'm trying to run this code to test the pseudo-random function

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    int count = 0;
    while (count < 10){
        srand(time(NULL));
        cout << rand() << ' ';
        cout << (time( NULL )) << " \n";
        count++;
    }
    return 0;
}

The output from this is 10 equal lines. This is not really the problem, as the seed here is the same, so the result should be the same. The problem is that if I run this program again it gives 10 very similar lines with little variation not only on the time() output, but on the rand output too.

The srand(time(NULL)) is giving very similar answers that are basically the same return value, only a little bigger.

(Returning 9631 on first run, and then 9656 on the second).

My question is, is that the expected behavior? And how can I get more different results like 38 on the first run, and 671 on the second?

Foi útil?

Solução 3

To make a random number with a nearly the same seed(time), you can add a static variable to make rand() behaves different even with same parameter; or, you can make the parameter change when you get same time. For example:

int t=0;
...
rand(t=(t*7)^time(NULL));

Outras dicas

Lots of misconceptions here... That the difference between two time(NULL) calls close to each other is small, is expected. After all, time moves only so fast. The next problem is that rand() returns a (pseudo) random value (of varying quality): Random in this case means that you may get 33 repeatedly a few times, as long as it's not predictable. That being said, rand() is implementation dependent, and it may very well be that your implementation uses something like an LCG, which doesn't generate good uniform random values. The only fix for that, is switching to a different rng. Since this is tagged as C++, you may want to take a look into C++11s random header and use something like their mersenne twister implementation, which is a good pseudo random number generator which produces random numbers with great quality and uniform distribution.

The difference between varying executions will presumably be a small difference of change in time. The results of rand can be different for different C runtimes, but here is the implementation of rand from Visual Studio 10.

int __cdecl rand ()
{
    _ptiddata ptd = _getptd();

    return( ((ptd->_holdrand = ptd->_holdrand * 214013L
        + 2531011L) >> 16) & 0x7fff );
}

Where holdrand stores the seed to start to start of with. This is a linear congruential generator which typically don't produce high quality randomness. It's also throwing away a lot of state each time which doesn't help.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top