random.randint shows different output in Python 2.x and Python 3.x with same seed

后端 未结 3 1326
旧时难觅i
旧时难觅i 2021-02-14 20:22

I am porting the application from python 2 to python 3 and encountered the following problem: random.randint returns different result according to used Python versi

3条回答
  •  遥遥无期
    2021-02-14 20:40

    The difference is caused by two things:

    1. You should use random.seed(42, version=1)
    2. In python 3.2 there was a change to random.randrange, which is called by random.randint and probably add to above issue.

    So use something like:

    try: random.seed(42, version=1)  # Python 3
    except TypeError: random.seed(42)  # Python 2
    

    and int(1+random.random()*99).

    More detail

    Backward compatibility was on purpose dropped with the change of randrange, see the original issue.

    See this reddit post.

    If possible use numpy.randomlike is proposed in the reddit post.

    Use of random.seed(42, version=1) as described in the documentation will cause random.random() to deliver the same result but give a different result for random.randint(1,100) (because in python 3.2 some problem with the old implementation was fixed). You may opt to only rely on something like int(1+random.random()*99).

    (Python 2 will run out of support very soon, soon2 or here. If possible check, if backward compatibility is really needed.)

    My current tests:

    import random 
    
    try: random.seed(42, version=1)  # Python 3
    except TypeError: random.seed(42)  # Python 2
    print(random.random())
    print(int(1+99*random.random()))
    print(random.randint(1,99))
    

    Results on Python 2

    0.639426798458
    3
    28
    

    and Python 3

    0.6394267984578837
    3
    36
    

提交回复
热议问题