cross python version randomness

Pavol Lisy pavol.lisy at gmail.com
Tue Mar 21 05:43:46 EDT 2017


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
>>
>> C:\code\hg-repos\reportlab>\python33\python s.py
>> 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit
>> (AMD64)] 0 24
>> 1 16
>> 2 12
>> 3 13
>> 4 22
>>
>> However, when I use random.random() all seems to be the same so this
>> script C:\code\hg-repos\reportlab>cat u.py
>> import sys, random
>> print(sys.version)
>> random.seed(103)
>> for i in range(5):
>>      print(i, random.random())
>>
>> seems to be fine
>>
>>
>> C:\code\hg-repos\reportlab>\python27\python u.py
>> 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit
>> (AMD64)] (0, 0.9790501200727744)
>> (1, 0.45629827629184827)
>> (2, 0.7188470341002364)
>> (3, 0.7348862425853395)
>> (4, 0.21490166849706338)
>>
>> C:\code\hg-repos\reportlab>\python33\python u.py
>> 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit
>> (AMD64)] 0 0.9790501200727744
>> 1 0.45629827629184827
>> 2 0.7188470341002364
>> 3 0.7348862425853395
>> 4 0.21490166849706338
>>
>> presumably randint is doing something different to get its values.
>
>
> The docs [https://docs.python.org/3/library/random.html#random.randrange]
> for randrange have this note:
>
> Changed in version 3.2: randrange() is more sophisticated about producing
> equally distributed values. Formerly it used a style like int(random()*n)
> which could produce slightly uneven distributions.
>
> Maybe that's the explanation?  Unfortunately I don't have an install of
> 3.0/1 to test against.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>

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.



More information about the Python-list mailing list