差异是由两件事造成的:
- 你应该使用
random.seed(42, version=1)
- 在 python 3.2 中,有一个更改
random.randrange
,这被称为random.randint
并可能添加到上面issue https://docs.python.org/3/library/random.html#random.randrange.
所以使用类似的东西:
try: random.seed(42, version=1) # Python 3
except TypeError: random.seed(42) # Python 2
and int(1+random.random()*99)
.
更多详情
随着以下内容的更改,故意放弃了向后兼容性randrange
,看原文issue https://bugs.python.org/issue9025.
看到这个reddit https://www.reddit.com/r/pythontips/comments/5pp5mz/the_random_module_with_the_same_seed_produces_a/ post.
如果可能的话使用numpy.random
就像 Reddit 帖子中提出的那样。
Use of random.seed(42, version=1)
如中所述文档 https://docs.python.org/3/library/random.html#bookkeeping-functions会引发random.random()
提供相同的结果,但给出不同的结果random.randint(1,100)
(因为在 python 3.2 中,旧实现的一些问题已得到修复)。您可以选择只依赖类似的东西int(1+random.random()*99)
.
(Python 2 将很快失去支持soon https://www.python.org/dev/peps/pep-0373/, soon2 https://github.com/python/devguide/pull/344 or here https://pythonclock.org。如果可能的话检查是否确实需要向后兼容性。)
我当前的测试:
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))
Python 2 上的结果
0.639426798458
3
28
和Python 3
0.6394267984578837
3
36