A small problem with qRand().
-
Hi everybody,
This is my first post, so it's going to be simple ;)
Well, in one of my app, I need to generate a big random number, the problem is qRand() can not pass RAND_MAX ( equal mostly to 2^15 ).
So, my question is : how can I generate a number greater than RAND_MAX with the Qt way ?
Before leaving I thank you for all possible answers.
-
May be you can use "qHash":http://doc.trolltech.com/4.8-snapshot/qhash.html#related-non-members with "qint64 QDateTime::currentMSecsSinceEpoch ":http://doc.trolltech.com/4.8-snapshot/qdatetime.html#currentMSecsSinceEpoch as input or
@ qRand() * QDateTime::currentMSecsSinceEpoch() @
-
You could try to generate two or three random numbers, multiply the first two and optionally add the third to it, or use some other way of combining the results (bitshifting and or-ing comes to mind).
-
First of all, I thank both of you for replying.
Andre : generating a random number and multiply/add it with another one, will reduce the equiprobability, that's why I avoided this solution.
task_struct : I realy don't know how to use QHach to generate a random number.
and for :
@qRand() * QDateTime::currentMSecsSinceEpoch()@
I think it doesn't make any difference because qRand() won't pass RAND_MAX.
I'll try and let you know. -
@Ouss4: yes, you are right. I am not sure if the bitshift trick would prevent that. At first sight, I'd say it does, but I might be off there.
-
May I ask for the purpose for such large random numbers? Is it about generating unqiue identifiers? Is it about statistics (as you menitoned equiprobability)? Or is it about cryptograpy? Probably qRand() isn't sufficient at all for your use case.
-
[quote author="Andre" date="1318432218"]@Ouss4: yes, you are right. I am not sure if the bitshift trick would prevent that. At first sight, I'd say it does, but I might be off there.[/quote]
AFAIK bitshifting should do the trick:
@
int randNumber = (qRand() << 16) + qRand();
@ -
Thanks guys, I'm going to try with bitshifting.
-
Thanks
[quote author="Gerolf" date="1318433239"][quote author="Andre" date="1318432218"]@Ouss4: yes, you are right. I am not sure if the bitshift trick would prevent that. At first sight, I'd say it does, but I might be off there.[/quote]AFAIK bitshifting should do the trick:
@
int randNumber = (qRand() << 16) + qRand();
@
[/quote] -
Or you could go the portable way and use srand() / rand()?
-
Which OS are you using? Under any 32-bit Linux I have access RAND_MAX is 2^32 - 1.