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

问题描述 投票:0回答:1
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生成不同种子的本地Threads,每个种子也被随机化,而不是仅仅递增整数值。 (尽管我认为后者没有区别)

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

python random
1个回答
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())
© www.soinside.com 2019 - 2024. All rights reserved.