Why is seeding the random generator not stable between versions of Python?

谁说我不能喝 提交于 2019-11-30 10:58:45

I was looking through What's New in Python 3.2 (because of this question), and I found:

The random.seed() function and method now salt string seeds with an sha512 hash function. To access the previous version of seed in order to reproduce Python 3.1 sequences, set the version argument to 1, random.seed(s, version=1).

It appears to be a breaking change (from 3.1 to 3.2) with a backwards compatibility option.

(As borrible pointed out, because a compatible seeder is offered the documentation contract has not been violated.)

The docs for seed say that they use the hash function to convert strings to valid input seeds. When I tested various versions of Python2.X (don't have 3 installed at the moment), some versions gave different values for hash(str(1)) Note that the docs for seed say that, regardless of version, they use the hash value for the string. You might want to pass an int instead (in addition to @pst 's point about using the backwards-compatible version of seed).

Snippet from the random module docs for 3.2:

If x is an int, it is used directly.

With version 2 (the default), a str, bytes, or bytearray object gets converted to an int and all of its bits are used. With version 1, the hash() of x is used instead.

(x here is the initializer for seed)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!