随机数的再现性(Python2/random)
Reproducibility of random numbers (Python 2/random)
在Python 2 documentation of the random.seed()
函数中我发现了一个警告:
If a hashable object is given, deterministic results are only assured
when PYTHONHASHSEED is disabled.
从https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHASHSEED我推断解释器的-R
开关可能具有与PYTHONHASHSEED
类似的效果。
我已经根据经验验证,用小整数作为种子的随机数似乎是可重现的。小整数的散列也是如此。
但是,int
是可哈希的。是否在任何可信来源中明确说明将其用作可重现随机数序列的种子是安全的?
与Reproducibility of python pseudo-random numbers across systems and versions?相比,同一系统和解释器内的可重复性就足够了。
不是完整的答案,但 random_seed
(in C) 的源代码是相关的:
if (PyInt_Check(arg) || PyLong_Check(arg))
n = PyNumber_Absolute(arg);
else {
long hash = PyObject_Hash(arg);
if (hash == -1)
goto Done;
n = PyLong_FromUnsignedLong((unsigned long)hash);
}
这表明除了 long
(int) 之外的任何东西都直接使用散列值作为种子,所以只要:
hash(int)
给出了一致的结果并且
- 您正在使用 seed 的这个实现(对于 Jython 等可能不一样)
然后我希望 seed(int)
产生一致的结果。
那是说我不能说这些条件中的任何一个保持不变,所以除非有人可以验证它们,否则这并不能真正给出明确的答案。
文档确认其在 Python 2.6 中的安全性:
If x is not None or an int or long, hash(x) is used instead. If x is an int or long, x is used directly.
(来自 https://docs.python.org/2.6/library/random.html#random.seed)
[编辑]
2.7 的文档已更新为:
If a is not None or an int or a long, then hash(a) is used instead. Note that the hash values for some types are nondeterministic when PYTHONHASHSEED is enabled.
在Python 2 documentation of the random.seed()
函数中我发现了一个警告:
If a hashable object is given, deterministic results are only assured when PYTHONHASHSEED is disabled.
从https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHASHSEED我推断解释器的-R
开关可能具有与PYTHONHASHSEED
类似的效果。
我已经根据经验验证,用小整数作为种子的随机数似乎是可重现的。小整数的散列也是如此。
但是,int
是可哈希的。是否在任何可信来源中明确说明将其用作可重现随机数序列的种子是安全的?
与Reproducibility of python pseudo-random numbers across systems and versions?相比,同一系统和解释器内的可重复性就足够了。
不是完整的答案,但 random_seed
(in C) 的源代码是相关的:
if (PyInt_Check(arg) || PyLong_Check(arg))
n = PyNumber_Absolute(arg);
else {
long hash = PyObject_Hash(arg);
if (hash == -1)
goto Done;
n = PyLong_FromUnsignedLong((unsigned long)hash);
}
这表明除了 long
(int) 之外的任何东西都直接使用散列值作为种子,所以只要:
hash(int)
给出了一致的结果并且- 您正在使用 seed 的这个实现(对于 Jython 等可能不一样)
然后我希望 seed(int)
产生一致的结果。
那是说我不能说这些条件中的任何一个保持不变,所以除非有人可以验证它们,否则这并不能真正给出明确的答案。
文档确认其在 Python 2.6 中的安全性:
If x is not None or an int or long, hash(x) is used instead. If x is an int or long, x is used directly.
(来自 https://docs.python.org/2.6/library/random.html#random.seed)
[编辑]
2.7 的文档已更新为:
If a is not None or an int or a long, then hash(a) is used instead. Note that the hash values for some types are nondeterministic when PYTHONHASHSEED is enabled.