蒙特卡洛模拟

 时间:2026-02-12 02:27:43

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

蒙特卡洛模拟

  • 如何使用R语言中的函数控制折线图折线点形状
  • 怎样用excel产生整数随机数
  • 如何用Excel制作直方图?
  • office Excel统计函数讲解:FDIST
  • Excel2007如何加载宏进行数据分析
  • 热门搜索
    稻城亚丁旅游价格 石家庄旅游团 qq旅游图标怎么点亮 海南旅游股票 大理丽江旅游攻略 重庆旅游必去的地方 壶口瀑布旅游 合肥旅游团 江门大方旅游 中国旅游研究院