-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmonte_carlo.py
87 lines (77 loc) · 2.35 KB
/
monte_carlo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import pylab
#set line width
pylab.rcParams['lines.linewidth'] = 4
#set font size for titles
pylab.rcParams['axes.titlesize'] = 20
#set font size for labels on axes
pylab.rcParams['axes.labelsize'] = 20
#set size of numbers on x-axis
pylab.rcParams['xtick.labelsize'] = 16
#set size of numbers on y-axis
pylab.rcParams['ytick.labelsize'] = 16
#set size of ticks on x-axis
pylab.rcParams['xtick.major.size'] = 7
#set size of ticks on y-axis
pylab.rcParams['ytick.major.size'] = 7
#set size of markers, e.g., circles representing points
pylab.rcParams['lines.markersize'] = 10
#set number of times marker is shown when displaying legend
pylab.rcParams['legend.numpoints'] = 1
import random, numpy
def throwNeedles(numNeedles):
inCircle = 0
for Needles in range(1, numNeedles + 1, 1):
x = random.random()
y = random.random()
if (x*x + y*y)**0.5 <= 1.0:
inCircle += 1
return 4*(inCircle/float(numNeedles))
def getEst(numNeedles, numTrials):
estimates = []
for t in range(numTrials):
piGuess = throwNeedles(numNeedles)
estimates.append(piGuess)
sDev = numpy.std(estimates)
curEst = sum(estimates)/len(estimates)
print('Est. = ' + str(curEst) +\
', Std. dev. = ' + str(round(sDev, 6))\
+ ', Needles = ' + str(numNeedles))
return (curEst, sDev)
def estPi(precision, numTrials):
numNeedles = 1000
sDev = precision
while sDev >= precision/2:
curEst, sDev = getEst(numNeedles, numTrials)
numNeedles *= 2
return curEst
random.seed(0)
estPi(0.005, 100)
def integrate(f, a, b, step):
yVals, xVals = [], []
xVal = a
while xVal <= b:
xVals.append(xVal)
yVals.append(f(xVal))
xVal += step
pylab.plot(xVals, yVals)
pylab.title('sin(x)')
pylab.xlim(a, b)
xUnders, yUnders, xOvers, yOvers = [],[],[],[]
for i in range(500):
xVal = random.uniform(a, b)
yVal = random.uniform(0, 1)
if yVal < f(xVal):
xUnders.append(xVal)
yUnders.append(yVal)
else:
xOvers.append(xVal)
yOvers.append(yVal)
pylab.plot(xUnders, yUnders, 'ro')
pylab.plot(xOvers, yOvers, 'ko')
pylab.xlim(a, b)
ratio = len(xUnders)/(len(xUnders) + len(yUnders))
print(ratio)
print(ratio*b)
def one(x):
return 0.9
#integrate(one, 0, math.pi, 0.001)