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())
Why do the approximated pi values get smaller when I distribute the load over more threads?
First I thought it may be because of using the same seed, so I generate differently seeded local Random
s for each Thread
, which each seed being randomised as well instead of just being incrementing integer values.
(Even though I don't think the latter part made the difference)
But the problem still persists. Does anyone know the reason for that behaviour?