为什么减小 np.linspace 的范围会提高数值积分的精度?

Why does decreasing the range of np.linspace increase the accuracy of numerical integration?

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

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)

这个returns值为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)

这 returns 更准确的值为 1.0000102809119051。为什么会这样?

两件事:

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

  • 在你的第一种方法中,错误主要是左右半杆过冲,即(b-a)/(N-1)/2 * f(a)(b-a)/(N-1)/2 * f(b)。如果你减去这两个,你得到的准确性与你的第二种方法相当。