MonteCarlo方法求积分与解析方法的对比验证

蒙特卡洛积分是一种通过随机抽样来估计定积分的方法。我们可以用它来近似计算函数 $y=x^2$在某个区间上的积分,并基于此结果绘制出其积分函数的图像。 为了验证蒙卡的计算效果,我们在同一张图中给制出蒙卡积分结果和解析解析的结果,对比结果可以证实蒙特卡洛方法的可行性。代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#! /usr/bin/env python3
# vim:fenc=utf-8
import numpy as np
import matplotlib.pyplot as plt

# 定义蒙特卡洛积分函数
def monte_carlo_integration(func, a, b, n=1000):
    x_samples = np.random.uniform(a, b, n)
    y_samples = func(x_samples)
    # 计算平均高度
    average_height = np.mean(y_samples)
    # 计算积分值
    integral = average_height * (b - a)
    return integral

# 定义被积函数
def f(x):
    return x**2

# 解析解计算积分函数
def analytic_integral_f(x,a):
    return (x**3)/3-(a**3)/3

# 使用蒙特卡洛方法求解积分
a, b = -5, 5  # 积分区间
x_points = np.linspace(a, b, 100)  # 用于绘图的x点
monte_carlo_values = []

for i in range(len(x_points)):
    # 对每个x点计算从a到该点的积分
    integral_value = monte_carlo_integration(f, a, x_points[i], n=20000)
    monte_carlo_values.append(integral_value)

# 计算解析解
analytic_values = analytic_integral_f(x_points,a)

# 绘制积分后的函数图像
plt.figure(figsize=(10, 8))
plt.plot(x_points, monte_carlo_values, label='Monte Carlo Integral of $x^2$', color='blue', linestyle='--')
plt.plot(x_points, analytic_values, label='Analytical Integral of $x^2$', color='red')

# 添加标题和标签
plt.title('Comparison between Monte Carlo and Analytical Integration of $x^2$')
plt.xlabel('x')
plt.ylabel('Integral Value')

# 显示图例
plt.legend()

# 显示网格
plt.grid(True)

# 显示图像
plt.show()