本文主要是介绍蒙特卡洛模拟计算圆周率和积分,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
蒙特卡洛模拟计算圆周率
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Circlen = 1000
r = 1.0
a,b = (0.0,0.0)xmin,xmax = a-r,a+r
ymin,ymax = b-r,b+rx = np.random.uniform(xmin,xmax,n)
y = np.random.uniform(ymin,ymax,n)fig = plt.figure(figsize=(6,6))axes = fig.add_subplot(1,1,1)
plt.plot(x,y,'ro',markersize=1)
plt.axis('equal')d =np.sqrt( (x-a)**2+(y-b)**2)
res = sum(np.where(d<r,1,0))pi = 4*res/n
picircle = Circle(xy = (a,b),radius = r,alpha = 0.5,color='gray')
axes.add_patch(circle)
plt.grid(True,linestyle="--",linewidth="0.8")
plt.show()
蒙特卡洛模拟计算积分
#蒙特卡洛模拟计算积分
n = 100000
xmin,xmax = (0.0,1.0)
ymin,ymax = (0.0,1.0)x = np.random.uniform(xmin,xmax,n)
y = np.random.uniform(ymin,ymax,n)def f(x):return x**2
res = sum(np.where(y<f(x),1,0))integral = res/n
integralfig = plt.figure(figsize=(6,6))axes = fig.add_subplot(1,1,1)
plt.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()
这篇关于蒙特卡洛模拟计算圆周率和积分的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!