算法基础--蒙特卡洛模拟

蒙特·卡罗方法(Monte Carlo method),也称统计模拟方法,是二十世纪四十年代中期由于科学技术的发展和电子计算机的发明,而被提出的一种以概率统计理论为指导的一类非常重要的数值计算方法。是指使用随机数(或更常见的伪随机数)来解决很多计算问题的方法。与它对应的是确定性算法。蒙特·卡罗方法在金融工程学,宏观经济学,计算物理学(如粒子输运计算、量子热力学计算、空气动力学计算)等领域应用广泛。本经验演示其应用。

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

import numpy
import matplotlib
import math
from numpy import power
#生成100000个坐标落在x(0,1),y(0,1)的随机点
x=numpy.random.uniform(0,1,100000)
y=numpy.random.uniform(0,1,100000)
#初始化落在圆中的点个数计数器
count=0
#在100000个点中,循环比较每个点跟(0.5,0.5)点的距离,判断是否落在圆中,是,则计数器加1
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值
PI=count/float(len(x))*4
#计算蒙特卡洛模拟PI值与实际PI值的偏差率
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()

在这里插入图片描述
在这里插入图片描述
将模拟点增加十倍:
在这里插入图片描述

2)数值积分。
对复杂函数的积分,可以使用此方法,误差是存在的。但是方便快捷。
与第一个例子类似,也是抽样分析。分析点落在积分面积的概率。
以y=x**2为例:

import numpy
from numpy import power
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=x**2
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))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43622668/article/details/84317523