# 使用蒙特卡洛方法求解积分 a, b = -5, 5# 积分区间 x_points = np.linspace(a, b, 100) # 用于绘图的x点 monte_carlo_values = []
for i inrange(len(x_points)): # 对每个x点计算从a到该点的积分 integral_value = monte_carlo_integration(f, a, x_points[i], n=20000) monte_carlo_values.append(integral_value)
# 绘制积分后的函数图像 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')