difference between random module in python 2.6 and 3.2?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Feb 6 05:01:05 CET 2012


On Mon, 06 Feb 2012 02:27:38 +0100, Matej Cepl wrote:

> Strange thing is that this unit tests correctly with python3, but fails
> with python2. The problem is that apparently python3 random.choice picks
> different element of self[k] than the one python2 (at least, both of
> them are constant in their choice).

Confirmed:

steve at runes:~$ python2.6 -c "from random import choice, seed; seed(1); 
print choice(range(1000))"
134
steve at runes:~$ python3.2 -c "from random import choice, seed; seed(1); 
print(choice(list(range(1000))))"
137

steve at runes:~$ python2.6 -c "from random import choice, seed; seed(42); 
print choice(range(1000))"
639
steve at runes:~$ python3.2 -c "from random import choice, seed; seed(42); 
print(choice(list(range(1000))))"
654


> Is it known that there is this difference? Is there a way how to make
> both random.choice select the same?

Reading the docs, I would expect that when using an int as seed, you 
should get identical results. There is no mention that the PRNG has 
changed between 2.6 and 3.2; both should use the given int as seed. There 
is a change of behaviour when using strings/bytes/bytearrays, and 
Python3.2 provides a "version=N" argument to seed to set the old 
behaviour. But this doesn't apply to integer seeds.

I call this a bug.

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

steve at runes:~$ python3.1 -c "from random import choice, seed; seed(42); 
print(choice(list(range(1000))))"
639
steve at runes:~$ python3.1 -c "from random import choice, seed; seed(1); 
print(choice(list(range(1000))))"
134


-- 
Steven



More information about the Python-list mailing list