kkirtac wrote:
> Hello, i m using the standard rand() function to generate several
> random numbers. Even if i seed the generator before the loop
> "srand( (unsigned)time( NULL ) );" , it usually selects a previously
> selected number in the process, after 6-7 iterations, i want the
> sequence to be unique..should i consider some further modifications in
> the code to achieve my goal maybe ? here is the piece of code..
>
> vector<int> rands ;
> int rnd ; //random number
> srand( (unsigned)time( NULL ) );
> int range_max = 165, range_min = 0 ;
> for( int i = 0; i < 15 ; i++ )
> {
> rnd = (double)rand() / (RAND_MAX + 1) * (range_max-1 -range_min) +
> range_min;
> rands.push_back(rnd);
> }
>
> it usually chooses a previously selected random number after 7-8
> iterations, not all the time but usually..
Even with a perfect random number generator, this may well happen, due to a
thing called the "birthday paradox":
http://en.wikipedia.org/wiki/Birthday_paradox
This states (in terms applicable here) that given 23 numbers randomly chosen
from the range [1,365] it is more likely than not that they will be nonunique.
IOW, given 23 random people, it is more likely than not that two share a birthday.
In your case, given a perfect rand() the probability that 8 numbers will be
unique in the range [1,165] is 80.1%. That's more likely than not, but about 1
time in 5 you'll have collisions.
You should modify your code to prevent collisions entirely if you wish to avoid
them entirely. This is comp.lang.c FAQ question 13.19; see
http://c-faq.com/ for
details.
Phil
--
Philip Potter pgp <at> doc.ic.ac.uk