为什么同时使用多个PRNG会产生偏差的结果?

时间:2019-04-05 17:48:23

标签: python random

import random as r
from random import Random
from threading import Thread
#ap = amount of random points
#load_split = how many threads are tasked with it
def pi(ap=1000000,load_split=16):
#circle hits
    c,=0,
#chooses a random point and sees if it is in the circle
    def t(seed,ap=ap/load_split):
        nonlocal c
        r = Random()
        r.seed(seed)
        while ap>0:
            if ((r.random()-0.5)**2+(r.random()-0.5)**2)**0.5<=0.5: c+=1
            ap-=1
    th = []
    for i in range(load_split):
        thr = Thread(target=t,args=[r.random()*i])
        thr.start()
        th.append(thr)
#executes the random tries lost to the threads
    for i in range(ap%load_split): 
        if ((r.random()-0.5)**2+(r.random()-0.5)**2)**0.5<=0.5: c+=1
#waiting for threads to complete
    for i in th: i.join()
    return 4 * c / ap
input(pi())

当我在更多线程上分配负载时,为什么近似pi值会变小?

首先,我认为可能是因为使用了相同的种子,所以我为每个Random生成了不同种子的本地Thread,每个种子也被随机化,而不仅仅是增加整数值。 (即使我不认为后一部分有所作为)

但是问题仍然存在。有人知道这种行为的原因吗?

1 个答案:

答案 0 :(得分:0)

import random as r
from random import Random
from threading import Thread
def pi(ap=8000000,load_split=4):
    c=[]
    for i in range(load_split): c.append(0)
#now each thread writes to its own circle hit count
    def t(seed,ap=ap/load_split):
        r = Random()
        r.seed(seed)
        while ap>0:
            if ((r.random()-0.5)**2+(r.random()-0.5)**2)**0.5<=0.5:
                c[seed]+=1
            ap-=1
    th = []
    for i in range(load_split):
        thr = Thread(target=t,args=[i])
        thr.start()
        th.append(thr)
    for i in range(ap%load_split): 
        if ((r.random()-0.5)**2+(r.random()-0.5)**2)**0.5<=0.5: c+=1
    for i in th: i.join()
    return 4 * sum(c) / ap
input(pi())