蒙特卡洛方法的使用:计算pi值与积分计算

参考: 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()

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值