Random Number

Tim Delaney tcdelaney at optusnet.com.au
Sat Mar 27 17:55:40 EST 2004


"james blair" wrote:

> Whats the possibility that the numbers generated will be same when
> generated by 100 users at the same time?

This has already been answered.

> Whats the best method to generate random numbers so that they are most
> likely unique??

Realy, there's no "most likely" way. You can either rely on the random
number generator (mersenne twister, which is pretty damn good) or you can
guarantee that they are unique by a couple of methods:

1. Keep track of which numbers have been generated, and if you get a repeat
re-generate it - works well if the total number of numbers to be generated
is small and the range is large;

2. Keep track of all the possible values, and as each one is chosen
eliminate it from the future possible values. Select values using
random.choice();

3. If you know the maximum number of random values you will ever generate,
and you want to guarantee no collisions, Python 2.3 has a superb way of
doing it ...

    >>> import random
    >>> random.sample(xrange(1000000000), 5)
    [463302274, 701637929, 319795767, 173458898, 500806835]

and you can then just hand out the values in order ...

    >>> import random
    >>> rand_values = iter(random.sample(xrange(1000000000), 5))
    >>> rand_values.next()
    724415074
    >>> rand_values.next()
    316181550
    >>> rand_values.next()
    107217351
    rand_>>> rand_values.next()
    828888162
    >>> rand_values.next()
    599821642
    >>> rand_values.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration

Note that there is one fewer zero in there than you want because ...

    >>> import random
    >>> random.sample(xrange(10000000000), 5)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    OverflowError: long int too large to convert to int

Tim Delaney





More information about the Python-list mailing list