用蒙特卡洛方法计算定积分
1.原理
计算定积分

利用蒙特卡洛计算方法,核心步骤是求取随机的 g(X1),………,g(Xn),n∈[a,b],由数学期望和大数定理可以近似计算定积分,公式为

2.测试用例
原函数:

导函数:

计算导函数在[10,15]上的定积分;
3.测试语言
Python
4.测试代码
#Monte Carlo Method for Calculating Definite Integral
import math
import random
#积分区间
upper_bound=15
lower_bound=10
#========================================================
#导函数
#========================================================
def f_x_(x):
outcome=3*(x**2)+4*math.cos(x)-4*x*math.sin(x)
return outcome
#========================================================
#原函数
#========================================================
def F_x_(x):
outcome=x**3+4*x*math.cos(x)
return outcome
#========================================================
#生成随机数,用蒙特卡洛方法计算定积分
#========================================================
DefiniteIntegral_By_MonteCarloMethod=0
#随机生成10000个f(x),10<=x<=15,求和
sum=0
count=1
while count<=10000:
sum=sum+f_x_(random.uniform(lower_bound,upper_bound))
count=count+1
DefiniteIntegral_By_MonteCarloMethod=(upper_bound-lower_bound)*(sum/10000)
print("用蒙特卡洛方法计算的定积分:")
print(DefiniteIntegral_By_MonteCarloMethod)
print("")
#========================================================
#直接用原函数求定积分,用于比较结果的偏差程度
#========================================================
DefiniteIntegral_By_PrimitiveFunction=F_x_(upper_bound)-F_x_(lower_bound)
print("直接用原函数计算的定积分:")
print(DefiniteIntegral_By_PrimitiveFunction)
print("")
#========================================================
#偏差程度
#========================================================
math_deviation=abs(DefiniteIntegral_By_MonteCarloMethod-DefiniteIntegral_By_PrimitiveFunction)/DefiniteIntegral_By_PrimitiveFunction
print("偏差程度为:")
#显示百分比,小数点后保留四位
print('percent: {:.4%}'.format(math_deviation))
5.测试结果

用蒙特卡洛方法计算的定积分:
2366.508157479758
直接用原函数计算的定积分:
2362.9815863915287
偏差程度为:
percent: 0.1492%
网友评论