Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qrand is not generating a random number

Tags:

random

qt

I have a QT app, running 2 more threads.

Inside the threads I use the qrand function to generate a random number. The following is the code used to get the number, where m_fluctuations max is a double.

int fluctuate =  qrand() % (int)(m_FluctuationMax * 100);

I tried adding the following code in the main thread, and also inside the thread classes.

QTime now = QTime::currentTime();
qsrand(now.msec());

Now the problem is, that the values being generated are always the same, each time the application is started.

Shouldn't they be different, since the seed is set by 'currentTime()'.

Thanks

like image 586
Michael Frey Avatar asked Dec 06 '22 02:12

Michael Frey


2 Answers

I had my qsrand() in the thread/class constructor. When i moved it to the run() function, it started to work randomly. Not sure why it would not work from the constructor though. Thanks everyone for your help.

like image 177
Michael Frey Avatar answered Jan 18 '23 07:01

Michael Frey


This may help anyone who happened to have a similar problem:

qsrand(static_cast<quint64>(QTime::currentTime().msecsSinceStartOfDay()));

array<int, 5> arr = {qrand(), qrand(), qrand(), qrand(), qrand()};

for(auto i : arr)
   cout << i << endl;
like image 45
Tyler Heers Avatar answered Jan 18 '23 09:01

Tyler Heers