蒙特卡洛模拟通俗理解_蒙特卡洛模拟
1、求解pi,在平面内随机采样,分布一定数量的点,点的分布服从均匀分布。通过求解一个点落在圆内的概率,就可以求出圆的面积与平面的面积之比,就可以求出圆周率。
【资料图】
2、代码演示和结果
3、x=numpy.random.uniform(0,1,100000)
4、y=numpy.random.uniform(0,1,100000)
5、count=0
6、for i in range(len(x)):
7、 d=math.sqrt(power((x[i]-0.5),2)+power((y[i]-0.5),2))
8、 if d=0.5:
9、 count+=1
10、PI=count/float(len(x))*4
11、delta=round((PI-math.pi)/math.pi*100,2)
12、print str(count)+" of"+str(len(x))+" points locate within circle:"
13、print "The calculated PI is:"+str(PI)
14、print "The theory value is:"+str(math.pi)
15、print "The deviation is:"+str(delta)+"%"
16、print "The area of circle is:"+str(count/float(len(x)))+" using Monte Carlo."
17、print "The area of circle is:"+str(round(math.pi*power(0.5,2),4))+" using theory value"
18、from matplotlib.patches import Circle
19、import matplotlib.pyplot as plt
20、figure=plt.figure()
21、ax=figure.add_subplot(111)
22、ax.plot(x,y,"ro",markersize=1)
23、circle=Circle(xy=(0.5,0.5),radius=0.5,alpha=0.5)
24、ax.add_patch(circle)
25、plt.show()
26、数值积分。
27、这种方法可用于复杂函数的积分,存在误差。但是方便快捷。
28、和第一个例子类似,也是抽样分析。分析点落在积分面积上的概率。
29、代码演示和结果
30、a=numpy.linspace(0,1,10000)
31、b=power(a,2)
32、figure=plt.figure()
33、ax=figure.add_subplot(111)
34、ax.plot(a,b,"b-")
35、plt.show()
36、f=lambda x:power(x,2)
37、x=numpy.random.uniform(0,1,1000000)
38、y=numpy.random.uniform(0,1,1000000)
39、count=0
40、for i in range(len(x)):
41、 if y[i]=f(x[i]):
42、 count+=1
43、print count/float(len(x))
44、print 1/float(3)
45、人口问题模拟
46、比如有些人为了生男孩而生二胎,那么这种策略会影响男女性别比吗?
47、代码如下:
48、n=10000
49、ratio=[]
50、dic={"male":0,"female":0}
51、for i in range(n):
52、 p=numpy.random.rand()
53、 if p0.5:
54、 dic["male"]+=1
55、 else:
56、 dic["female"]+=1
57、 while p0.5:
58、 p=numpy.random.rand()
59、 if p0.5:
60、 dic["female"]+=1
61、 else:
62、 dic["male"]+=1
63、 if dic["female"]!=0:
64、 ratio.append(dic["male"]/float(dic["female"]))
65、plot(ratio,"b-")
66、通过模拟,我们发现不会对其产生影响。男女比例大致为1:1。
以上就是蒙特卡洛模拟这篇文章的一些介绍,希望对大家有所帮助。
标签: