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
s,每个种子也被随机化,而不是仅仅递增整数值。 (尽管我认为后者没有区别)
但问题仍然存在。有谁知道这种行为的原因?
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())