Ivan
Ivan

Reputation: 31

Qt qrand in loop in Windows generate same numbers

I have qt application using qml. qrand in loop works wrong, in code works right. This problem appears only at windows(tried in windows 7 and 8 with with MSVC2012_OpenGL_32bit). Here is example:

In main.cpp at begin i print:

QTime time = QTime::currentTime();
qsrand((uint)time.msec());

then in loop i use qrand

for (int j = 0; j < 4; j++)
{
    for (int i = 0; i < 1000; i++)
    {
        int r1 = qrand() % 150;
        int r2 = qrand() % 150;
        qDebug() << r1 << r2 << endl;
    }
}

in output there are 2 different numbers repeats about 200 times, then changes:

8 58
8 58
8 58
...
120 1
120 1
120 1
...

if i use qrand not in loop, it works right. But, if i make function, that generates random numbers with qrand this function works wrong. In linux on gcc 64 bit compiler the same code works right, it generates different numbers in every line. In windows 7 and 8 with MSVC2012_OpenGL_32bit qrand works wrong. Also, i tried standard srand and rand(), it also works wrong. I checked (uint)time.msec(), it is always different. But if i put qsrand into loop program generates not perfect, but different numbers:

for (int j = 0; j < 4; j++)
{
    for (int i = 0; i < 1000; i++)
    {
        QTime time = QTime::currentTime();
        qsrand((uint)time.msec());
        int r1 = qrand() % 150;
        int r2 = qrand() % 150;
        qDebug() << r1 << r2 << endl;
    }
}

Output not perfect couse it qrand just generates different numbers more often, but again not always.

UPDATE: i tried c++11 random in windows and it works. I didn't try it in linux yet. But the question about qrand is still alive.

The c++11 random which i used: std random functions not working - Qt MinGw

Upvotes: 3

Views: 1875

Answers (2)

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

As random is base on the clock, if you use random in a loop (which is very fast) the clock doesn't change, and your numbers are all the same.

You should add a pause statement to let the clock change.

Upvotes: 1

Ivan
Ivan

Reputation: 31

My answer is using c++11 random lib: std random functions not working - Qt MinGw

I have no time for deep investigation of this question, so its the simplest way to solve this problem.

Upvotes: 0

Related Questions