What's wrong with this code snippet?

Dave Hansen iddw at hotmail.com
Thu Jan 5 17:19:46 CET 2006


On Thu, 5 Jan 2006 01:14:43 +0000 (UTC) in comp.lang.python, Karlo
Lozovina <_karlo_ at _mosor.net_> wrote:

>Dave Hansen <iddw at hotmail.com> wrote in 
>news:l8mor19a0kelraogseokc7qmqgafpda6ia at 4ax.com:
>
>> I'm not sure what rn is, but it looks like a standard library
>> random.Random object.  If so, I don't think you want to seed your PRNG
>> each time you use it -- your numbers might be much less random that
>> way.  If it is the standard library object, the PRNG is seeded when
>> the module is first imported, so you may not need to seed it at all.
>
>Yes, it is random module. So, what is the preferred way of seeding random 
>number generator? Just once in a file? Or something else?
>
>I just needed some "random" choices to be made, so I didn't dig much into 
>random module. Anyway, thanks for pointing this out, appreciated.

>From my reading of the library docs, when you import random the PRNG
is seeded (using the current time) for you automatically.  

If you call seed without a parameter, it will again use the current
time to seed the generator.  But the generator only needs one seed to
generate a random sequence.  Re-seeding the generator starts it
proding a new, different sequence. The resulting sequence of numbers
is really the first number in several distinct sequences.

It may be that the sequence of first numbers is "random enough" for
your use.  But the call to seed is useless at best, and damaging at
worst.

Unless you want to reproduce the same string of random numbers,
there's really no reason to seed the generator yourself.  Consider:

>>> rep = random.Random()
>>> rep.seed(1234)
>>> first = [rep.random() for x in range(10)]
>>> second = [rep.random() for x in range(10)]
>>> rep.seed(1234)
>>> third = [rep.random() for x in range(10)]
>>> print first == second
False
>>> print first == third
True
>>> fourth = [rep.random() for x in range(10)]
>>> print second == fourth
True
>>>  

In your code, I would simply remove the rn.seed() call.  Regards,
                                        -=Dave

-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list