I've been trying to write nice snippet of code to simulate pi estimation by randomly throwing darts on a dartboard. While running the following code on high but reasonable numbers my mac doesn't plot.
When looking at it I don't find the source of such a high complexity.
I checked similar questions like this but haven't been able to find straightforward answer.
My guess is that the line plotting real pi is computationally intense - but that's just a hunch.
I'd also appreciate any comment regarding style / efficiency.
import numpy as np
import random
import math
from matplotlib import pyplot as plt
def estimatePi(r,w,h,N):
center = (w/2.0,h/2.0)
in_circle = 0
for i in range(N):
x = random.uniform(0.0,w)
y = random.uniform(0.0,h)
distance = math.sqrt((x-center[0])**2+(y-center[1])**2)
if distance <= r:
in_circle += 1
outOfCircle=N-in_circle
ratio = float(in_circle)/N
#ratio = ((r**2)*pi)/(w*h) // *(w*h)
#ratio*(w*h) = ((r**2)*pi) // : r**2
pi = ratio*(w*h)/(r**2)
return pi
#run, aggregate results:
PiEstimation=[]
num_darts=[]
loopcount = 1000001
i=10000
while i <loopcount:
result=estimatePi(3,10,10,i)
num_darts.append(i)
PiEstimation.append(result)
i += 15000
# plot:
plt.title('Estimating the Value of Pi - Dartboard Simulation')
plt.plot([0,100000000], [3.14,3.14], 'k-',color="red", linewidth=2.0)
plt.ylabel('Pi Estimation')
plt.xlabel('Number of Darts')
plt.errorbar(num_darts,PiEstimation, yerr=.0001,ecolor='magenta')
plt.show('hold')