蒙特卡罗模拟
蒙特卡罗(Monte Carlo)方法,又称随机抽样或统计试验方法,是以概率和统计理论方法为基础的一种计算方法
使用随机数(或更常见的伪随机数)来解决很多计算问题的方法。
将所求解的问题同一定的概率模型相联系,用电子计算机实现统计模拟或抽样,以获得问题的近似解。
① π的计算
② 计算积分 y = x**2
③ 排队上厕所问题
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline
# π的计算from matplotlib.patches import Circle
n =10000# 投点次数
r =1.0# 半径
a, b =(0.,0.)# 圆心# 圆的信息
x_min, x_max = a-r, a+r
y_min, y_max = b-r, b+r
# 正方形区域边界
x = np.random.uniform(x_min, x_max, n)# 均匀分布
y = np.random.uniform(y_min, y_max, n)# 在正方形区域内随机投点# numpy.random.uniform(low,high,size) → 从一个均匀分布[low,high)中随机采样,均匀分布
d = np.sqrt((x-a)**2+(y-b)**2)
res =sum(np.where(d < r,1,0))# 计算点到圆心的距离# 统计落在圆内的点的数目
pi =4* res / n
print('pi: ', pi)# 计算 pi 的近似值 → Monte Carlo方法:用统计值去近似真实值
fig = plt.figure(figsize =(6,6))
axes = fig.add_subplot(1,1,1)
plt.plot(x,y,'ro',markersize =1)
plt.axis('equal')# 制图
circle = Circle(xy =(a,b),radius = r, alpha =0.5,color ='gray')
axes.add_patch(circle)
plt.grid(True, linestyle ="--",linewidth ="0.8")
plt.show()# 绘制圆形
# 计算积分 y = x**2
n =10000# 投点次数
x_min, x_max =0.0,1.0
y_min, y_max =0.0,1.0# 矩形区域边界
x = np.random.uniform(x_min, x_max, n)# 均匀分布
y = np.random.uniform(y_min, y_max, n)# 在矩形区域内随机投点deff(x):return x**2# 创建函数 y = x**2
res =sum(np.where(y < f(x),1,0))# 统计 落在函数 y=x^2图像下方的点的数目
integral = res / n
print('integral: ', integral)# 计算 定积分的近似值
fig = plt.figure(figsize =(6,6))
axes = fig.add_subplot(111)
axes.plot(x, y,'ro',markersize =1)
plt.axis('equal')# 绘制散点图
xi = np.linspace(0,1,100)
yi = xi **2
plt.plot(xi,yi,'--k')
plt.fill_between(xi, yi,0, color ='gray',alpha=0.5,label='area')
plt.grid()# 绘制 y = x**2 面积图
蒙特卡罗模拟蒙特卡罗(Monte Carlo)方法,又称随机抽样或统计试验方法,是以概率和统计理论方法为基础的一种计算方法使用随机数(或更常见的伪随机数)来解决很多计算问题的方法。将所求解的问题同一定的概率模型相联系,用电子计算机实现统计模拟或抽样,以获得问题的近似解。 ① π的计算 ② 计算积分 y = x**2 ③ 排队上厕所问题import numpy as npimport pandas as pdimport matplotlib.pyplot as plt% matp