【问题标题】:Why does decreasing the range of np.linspace increase the accuracy of numerical integration?为什么减小 np.linspace 的范围会提高数值积分的准确性?
【发布时间】:2020-01-25 17:00:23
【问题描述】:

阅读关于简单数值积分的教程 (https://helloacm.com/how-to-compute-numerical-integration-in-numpy-python/),这似乎表明减小函数中使用的 x 值的范围会返回更准确的数值答案。使用的代码是

def integrate(f, a, b, N):
    x = np.linspace(a, b, N)
    fx = f(x)
    area = np.sum(fx)*(b-a)/N
    return area

integrate(np.sin, 0, np.pi/2, 100)

这将返回一个值 0.99783321217729803。

但是,当他们将集成方法修改为:

def integrate(f, a, b, N):
    x = np.linspace(a+(b-a)/(2*N), b-(b-a)/(2*N), N)
    fx = f(x)
    area = np.sum(fx)*(b-a)/N
    return area

integrate(np.sin, 0, np.pi/2, 100)

这将返回更准确的值 1.0000102809119051。为什么会这样?

【问题讨论】:

  • 也许我读错了,但看起来步数保持不变,所以减小范围实际上会减小步长 -> 更准确
  • 但是改变积分范围不会改变答案吗?将 sin(x) 从 0 积分到 pi/2 = 1,但是从 0+k 积分到 pi/2-k
  • 你改变了采样点的范围,而不是积分范围:在你的area计算中你仍然使用(b-a),但是你在第二种情况的区间中有更多的点
  • 采样范围与积分范围有何不同?我会认为他们的意思是一样的。
  • 在第一种情况下,样本相对于积分箱的位置会发生变化。它从最左边的 bin 的左端开始,并以小步长向右移动。当到达最右边的 bin 时,它将移动到最右边的 bin 端。第二种情况在其中心对每个 bin 进行采样。 (这是二元线性被积函数的最佳位置。)

标签: python numpy numerical-integration


【解决方案1】:

两件事:

  • 第一个integrate 中的步长不是(b-a) / N,而是(b-a) / (N-1)

  • 在您的第一种方法中,误差主要由左右半条超调引起,即(b-a)/(N-1)/2 * f(a)(b-a)/(N-1)/2 * f(b)。如果您减去这两个,您将获得与第二种方法相当的准确度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 2016-08-02
    • 2017-08-10
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多