参考: https://blog.csdn.net/Cuixinyang19_/article/details/79888981
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 07:38:15 2019
@author: ylz
用此种方法对pi值进行估计,就是蒙特卡洛方法
https://blog.csdn.net/Cuixinyang19_/article/details/79888981
蒙特卡洛方法:
1,产生大量的数据样点
2,对数据样点进行依据条件进行分割,分类
3,用每个类别中样点数量的统计值,来计算某些参数.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
#用蒙特卡洛方法求取pi的近似值.
# 投点次数
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)
#计算点到圆心的距离
d = np.sqrt((x-a)**2 + (y-b)**2)
#统计落在圆内点的数目
res = sum(np.where(d < r, 1, 0))
#计算pi的近似值(Monte Carlo:用统计值去近似真实值)
pi = 4 * res / n #用此种方法对pi值进行估计,就是蒙特卡洛方法
print('pi: ',pi)
#画个图
fig = plt.figure()
axes = fig.add_subplot(111)
axes.plot(x, y,'ro',markersize = 1)
plt.axis('equal')
#防止图像变形
circle = Circle(xy=(a,b), radius=r ,alpha=0.5)
axes.add_patch(circle)
plt.show()
#用蒙特卡洛方法求取f(x)与x轴围城图形的面积
def f(x):
return x**3
n = 30000
#矩形边界区域
x_min, x_max = 0.0, 1.0
y_min, y_max = 0.0, 1.0
#在矩形区域内随机投点x
x = np.random.uniform(x_min, x_max, n)
#均匀分布
y = np.random.uniform(y_min, y_max, n)
#统计落在函数y=x^2下方的点
res = sum(np.where(y < f(x), 1 ,0)) #求该f(x)图形下的面积.
#计算定积分的近似值
integral = res / n
print('integeral: ', integral)
# 画个图
fig = plt.figure()
axes = fig.add_subplot(111)
axes.plot(x, y,'ro',markersize = 1)
plt.axis('equal')
# 防止图像变形
axes.plot(np.linspace(x_min, x_max, 10), f(np.linspace(x_min, x_max, 10)), 'b-')
# 函数图像 #plt.xlim(x_min, x_max)
plt.show()