【问题标题】:Integral using Monte Carlo Simulation yields incorrect result使用蒙特卡罗模拟积分会产生不正确的结果
【发布时间】:2018-05-14 21:44:31
【问题描述】:

我尝试计算 [0,2] 范围内的 exp(x) 和 x 的积分,并从统一的 dist 中采样。不知何故,积分结果恰好是预期值的一半。有谁知道我犯了哪一部分错误?谢谢!

x_upLimit=2
max = np.exp(x_upLimit)

def f(x):
    return np.exp(x)

def P_samples(N):
    return np.random.uniform(0, x_upLimit, N)

def expectation_value(N):
    s = P_samples(N)
    return sum(f(s))/N

# xs = np.linspace(0, 2)
# plt.plot(xs, np.array([max]*len(xs)))
# plt.plot(xs, f(xs), label ='f(x)')

#estimated
expectation_value(1000000) #3.1938802618
#expected
expr = integrate(exp(x), (x,0,2))
expected = expr.evalf() #6.38905609893065

回答我主人的问题。蒙特卡罗的积分是正确的。错误的地方是“集成”中使用的函数。应该是

#expected
expr = integrate(exp(x)*1/(2-0), (x,0,2))
expected = expr.evalf() #3.19452804946533

【问题讨论】:

    标签: python montecarlo


    【解决方案1】:

    exp(x) 在 0 和 2 之间计算的积分值实际上是 6.389...(由您使用的 integrate 函数给出)。

    问题在于你的 expectation_value 函数,它应该将函数平均值乘以积分范围(在这种特定情况下为 2)。请参阅here 了解详细说明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2013-07-23
      相关资源
      最近更新 更多