简体   繁体   English

如何随机设置随机种子?

[英]How do I set a random seed, randomly?

I am running a process which is massively parallelized that depends on randomness.我正在运行一个依赖于随机性的大规模并行化进程。 The trouble is that each of the workers in the parallel process shares the same random seed as the parent process, thereby ruining my attempts to run distinct random simulations.问题是并行进程中的每个工作进程与父进程共享相同的随机种子,从而破坏了我运行不同随机模拟的尝试。

Thus, I have the problem of how to set a distinct random seed on each worker at inception.因此,我遇到了如何在开始时为每个工人设置不同的随机种子的问题。 My current solution is to take the microseconds part off of time.time() and convert it to an integer before passing it to random.seed() .我目前的解决方案是将time.time()的微秒部分random.seed()并将其转换为整数,然后再将其传递给random.seed() It looks like the following.它看起来像下面这样。 Is there a better way?有没有更好的办法?

import re
import random
import time
def set_random_seed():
    seed = int(re.sub(r'[^0-9]', '', str(time.time())[-7:]))
    random.seed(seed)

See: https://docs.python.org/3/library/random.html#random.seed请参阅: https : //docs.python.org/3/library/random.html#random.seed

If the seed is omitted os.urandom will be used - if available.如果省略种子,将使用os.urandom - 如果可用。 You can just call:你可以打电话:

random.seed()

If you are worried about unlikely case of os.urandom being not available, generate unique seeds in your main process and pass one to each process you start.如果您担心os.urandom不太可能的情况不可用,请在您的主进程中生成唯一的种子并将一个传递给您启动的每个进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM