简体   繁体   English

子进程生成与父进程相同的“随机”数字

[英]Child processes generating same “random” numbers as parent process

I'm having some problems with simulations using concurrent.futures and np.random . 我在使用concurrent.futuresnp.random进行模拟时遇到了一些问题。

Example: 例:

import numpy as np
from concurrent.futures import ProcessPoolExecutor, as_completed
from time import sleep

def calc_g():
    sleep(1)
    u = np.random.uniform()
    print u

futures = {}
with ProcessPoolExecutor() as executor:

    for i in range(0,10):  
        job = executor.submit(calc_g)
        futures[job] = i

    for job in as_completed(futures):
        job.result()

My results in this simulations are: 我在这个模拟中的结果是:

python teste.py
0.590820857053
0.590820857053
0.590820857053
0.590820857053
0.890384312465
0.890384312465
0.890384312465
0.890384312465
0.391709923204
0.391709923204

If I remove the sleep function in the function calc_g() , results seem to be a little more random: 如果我删除函数calc_g()中的sleep函数,结果似乎更随机:

python teste.py
0.116725033305
0.919465043075
0.116725033305
0.116725033305
0.608303685887
0.59397039096
0.608862016487
0.800008484487
0.689917804793
0.116725033305

I think that it has to do with the generation of seeds that numpy uses. 我认为这与numpy使用的种子的产生有关。 Python generates forks from the main program and the same seed is copied to child processes. Python从主程序生成分支,同一种子被复制到子进程。 As generation process of random numbers is deterministic after the generation of seeds, values from np.random.uniform() are the same. 由于随机数的生成过程在生成种子后是确定性的,因此来自np.random.uniform()值是相同的。

Can someone explain this better, with examples? 有人可以通过例子更好地解释这一点吗?

How should I use np.random in parallel tasks to simulate randomness as coin tossing? 我应该如何在并行任务中使用np.random来模拟随机性作为抛硬币?

For independent streams of PRNGs in multiprocessing, give each process its own RandomState . 对于多处理中的独立PRNG流,为每个进程提供自己的RandomState The simplest fix, change this line: 最简单的修复,改变这一行:

u = np.random.uniform()

To this: 对此:

u = np.random.RandomState().uniform()

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

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