cross python version randomness

Robin Becker robin at reportlab.com
Tue Mar 21 08:03:18 EDT 2017


On 21/03/2017 09:43, Pavol Lisy wrote:
> On 3/21/17, Kev Dwyer <kevin.p.dwyer at gmail.com> wrote:
>> Robin Becker wrote:
>>
>>> Is there a way to get the same sequences of random numbers in python 2.7
>>> and python >= 3.3?
>>>
>>> I notice that this simple script produces different values in python 2.7
>>> and >=3.3
>>>
>>> C:\code\hg-repos\reportlab>cat s.py
>>> import sys, random
>>> print(sys.version)
>>> random.seed(103)
>>> for i in range(5):
>>>      print(i, random.randint(10,25))
>>>
>>> C:\code\hg-repos\reportlab>\python27\python s.py
>>> 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit
>>> (AMD64)] 0 25
>>> 1 17
>>> 2 21
>>> 3 21
>>> 4 13
>............
>
> This is inspiring Robin! :)
>
> import sys, random
> print(sys.version)
>
> def randint(a, b):
>     return int(random.random()*(b-a+1))+a
>
> random.seed(103)
> for i in range(5):
>     print(i, randint(10,25))
> 3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 12:22:00)
> [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
> 0 25
> 1 17
> 2 21
> 3 21
> 4 13
>
> Output seems to be same as in your 2.7 version :)
>
> So if you are sure that sequences of random.random are same then you
> could use it.
>
> You could also save a sequence to file and use it repeatedly. (if it
> is not performance problem for you)
>
> PL.
>
I'm not as inspired as you; for the present I have chickened out and just 
modified the 2.7 randrange method to monkeypatch the 3.x random.Random class. It 
seems to be ok and allows all the test code to use random.randint, but for small 
widths I think your function is correct.
-- 
Robin Becker



More information about the Python-list mailing list