蒙特卡洛模拟

2025-10-31 22:14:08

1、求解圆周率π,在平面中随机抽样,分布着一定数量的点,点的分布服从均匀分布。通过求解点落在圆内的概率,即可求解圆的面积与平面面积的比值,而求解出圆周率π。

蒙特卡洛模拟

2、代码演示及结果

x=numpy.random.uniform(0,1,100000)

y=numpy.random.uniform(0,1,100000)

count=0

for i in range(len(x)):

    d=math.sqrt(power((x[i]-0.5),2)+power((y[i]-0.5),2))

    if d<=0.5:

        count+=1

PI=count/float(len(x))*4

delta=round((PI-math.pi)/math.pi*100,2)

print str(count)+' of'+str(len(x))+' points locate within circle:'

print 'The calculated PI is:'+str(PI)

print 'The theory value is:'+str(math.pi)

print 'The deviation is:'+str(delta)+'%'

print 'The area of circle is:'+str(count/float(len(x)))+' using Monte Carlo.'

print 'The area of circle is:'+str(round(math.pi*power(0.5,2),4))+' using theory value'

from matplotlib.patches import Circle

import matplotlib.pyplot as plt

figure=plt.figure()

ax=figure.add_subplot(111)

ax.plot(x,y,'ro',markersize=1)

circle=Circle(xy=(0.5,0.5),radius=0.5,alpha=0.5)

ax.add_patch(circle)

plt.show()

蒙特卡洛模拟

蒙特卡洛模拟

蒙特卡洛模拟

3、数值积分。

对复杂函数的积分,可以使用此方法,误差是存在的。但是方便快捷。

与第一个例子类似,也是抽样分析。分析点落在积分面积的概率。

蒙特卡洛模拟

4、代码演示及结果

a=numpy.linspace(0,1,10000)

b=power(a,2)

figure=plt.figure()

ax=figure.add_subplot(111)

ax.plot(a,b,'b-')

plt.show()

f=lambda x:power(x,2)

x=numpy.random.uniform(0,1,1000000)

y=numpy.random.uniform(0,1,1000000)

count=0

for i in range(len(x)):

    if y[i]<=f(x[i]):

        count+=1

print count/float(len(x))

print 1/float(3)

蒙特卡洛模拟

蒙特卡洛模拟

5、人口问题模拟

例如某些人生二胎是为了,生男孩,那么采用这种策略会影响男女性别比例吗?

蒙特卡洛模拟

6、代码如下:

n=10000

ratio=[]

dic={'male':0,'female':0}

for i in range(n):

    p=numpy.random.rand()

    if p<0.5:

        dic['male']+=1

    else:

        dic['female']+=1

    while p>0.5:

        p=numpy.random.rand()

        if p>0.5:

            dic['female']+=1

        else:

            dic['male']+=1

    if dic['female']!=0:

        ratio.append(dic['male']/float(dic['female']))

plot(ratio,'b-')

通过模拟我们发现其实不会影响。男女比例大致为1:1

蒙特卡洛模拟

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢