Suresh
Suresh

Reputation: 9595

Unique random number sequence using qrand() and qsrand()

I want to generate unique random number sequence in QT, Using QDateTime::currentDateTime().toTime_t() as seed value, will qrand() generate unique random numbers?

Upvotes: 3

Views: 13708

Answers (3)

balpha
balpha

Reputation: 50908

No. qrand can only generate as many unique numbers as fit into an integer, so -- whatever the implementation -- you cannot count on uniqueness.

Also, knowing that a different seed creates a different random integer would yield a level of predictability that effectively makes qrand not random anymore.

Edit: I swear I'm not trying to make fun of you by posting a cartoon; I think this is a quite good explanation of the problem:

alt text
(source: dilbert.com)

Upvotes: 8

Caleb Huitt - cjhuitt
Caleb Huitt - cjhuitt

Reputation: 14941

Depending on how you store your session ids, you can generated a (mostly) guaranteed unique identifier by using a UUID. See the documentation for QUuid. Also be aware of this (bold added):

You can also use createUuid(). UUIDs generated by createUuid() are of the random type. Their QUuid::Version bits are set to QUuid::Random, and their QUuid::Variant bits are set to QUuid::DCE. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated by createUuid() will not be unique. But it is a very small chance.

I can vouch for the fact that those generated UUIDs won't necessarily be unique, so if you do need them to be unique, look into libuuid or something similar.

Upvotes: 6

Kitsune
Kitsune

Reputation: 9341

According to the Qt Documentation, QRand is just a thread-safe version of the standard rand(), I wouldn't assume the method used is any more secure/superior to that of rand() based on that description.

I think you need to use different terminology than 'unique' random numbers (no Psuedo-Random Number Generator will produce a unique stream, as input X will always produce output Y). What's the actual situation?

Upvotes: 0

Related Questions