在下面的代码中,我在 python 中实现了复合辛普森规则。我通过在 [0,pi/2] 上积分 f = sinx 并将所得绝对误差绘制为 n 的函数(对于 n 的适当范围的整数值)进行了测试。如下所示。现在我试图验证我的方法是否为 4 阶。为此,我需要绘制 n 与 n^(-4) 的关系,而不是绘制误差与 n 的关系,以显示两者具有相同的斜率。
from math import pi, cos, sin
from matplotlib import pyplot as plt
def simpson(f, a, b, n):
"""Approximates the definite integral of f from a to b by the composite Simpson's rule, using 2n subintervals """
h = (b - a) / (2*n)
s = f(a) + f(b)
for i in range(1, 2*n, 2):
s += 4 * f(a + i * h)
for i in range(2, 2*n-1, 2):
s += 2 * f(a + i * h)
return s * h / 3
diffs = {}
exact = 1 - cos(pi/2)
for n in range(1, 100):
result = simpson(lambda x: sin(x), 0.0, pi/2, n)
diffs[2*n] = abs(exact - result) # use 2*n or n here, your choice.
ordered = sorted(diffs.items())
x,y = zip(*ordered)
plt.autoscale()
plt.loglog(x,y)
plt.xlabel("Intervals")
plt.ylabel("Error")
plt.show()
这会导致我的错误图:
最佳答案
您可以通过再次调用 plt.loglog()
向绘图添加另一条线。因此,在 plt.show()
之前,您可以添加:
n = []
n_inv_4 = []
for i in range(1,100):
n.append(2*i)
n_inv_4.append(1.0 / ((2*i)**4))
plt.loglog(n, n_inv_4)
请注意,上述计算使用 (2*i) 来匹配 simpson
方法中使用的 (2*n)。
关于Python对数图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53381215/