Pergunta

So I'm trying to generate random integers inside functions, but it returns the same numbers. NUM_SOURCES == 5 and for all 5 repetitions it gives the same number despite srand(time(0)) being called. I tried the same without std::, but the result did not change.

Any suggestions?

std::srand(time(0)); //setting seed
    ...
    for (int i = 0; i < NUM_SOURCES; i++)
                         {
                             if (sourceDeq->at(i)->getCurrentBid() == NULL) // If the source is empty, generate a new order
                             {
                                 sourceDeq->at(i)->setCurrentBid(sourceDeq->at(i)->generateBid(systemTime));
                             }
                         }
    ...
    Bid* Source::generateBid(int sysTime)
    {
        bidAmount = bidAmount + 1;
        return new Bid(bidAmount, generateTimeCreation(sysTime), 0, 0, 0, getNumber());
    }
    ...

    int Source::generateTimeCreation(int sysTime)
    {
        srand(0);
        if (sLaw == UNIFORM)
            return (sysTime + std::rand() % 10);
        if (sLaw == EXPONENTIAL)
            return(sysTime + round((1 - exp(-(std::rand() % 100))) * 10));
    }
Foi útil?

Solução

srand(0); initializes the random number generator again, so it will have the same results, every time... Don't do it.

The whole point of calling with time(NULL) is to provide a random seed.

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