difference between random module in python 2.6 and 3.2?

Terry Reedy tjreedy at udel.edu
Mon Feb 6 06:07:04 CET 2012


On 2/5/2012 11:01 PM, Steven D'Aprano wrote:

> Reading the docs, I would expect that when using an int as seed, you
> should get identical results.

That is similar to expecting hash to be consistent from version to version.

> There is no mention that the PRNG has changed between 2.6 and 3.2;

There is at best an informal policy. This was discussed in
http://bugs.python.org/issue9025
Antoine argued that if there were a written policy, it should be limited 
to bug-fix releases within a version. I agree.

> It appears to be a bug in 3.2, because 3.1 gives the same results as 2.6:

This change is a side effect of fixing the bug of non-uniformity 
discussed in that issue. In any case, in 2.7 and probably 3.1:

     def choice(self, seq):
         """Choose a random element from a non-empty sequence."""
         return seq[int(self.random() * len(seq))]  # raises IndexError

whereas in 3.2:

     def choice(self, seq):
         """Choose a random element from a non-empty sequence."""
         try:
             i = self._randbelow(len(seq))
         except ValueError:
             raise IndexError('Cannot choose from an empty sequence')
         return seq[i]

The change was announced in What's New in 3.2

random
The integer methods in the random module now do a better job of 
producing uniform distributions. Previously, they computed selections 
with int(n*random()) which had a slight bias whenever n was not a power 
of two. Now, multiple selections are made from a range up to the next 
power of two and a selection is kept only when it falls within the range 
0 <= x < n. The functions and methods affected are randrange(), 
randint(), choice(), shuffle() and sample().

-- 
Terry Jan Reedy




More information about the Python-list mailing list