Python loglog图

时间:2018-11-19 19:16:30

标签: python

在以下代码中,我在python中实现了复合Simpsons规则。我通过在[0,pi / 2]上积分f = sinx并针对n的合适整数值范围绘制所得的绝对误差作为n的函数来进行测试。如下所示。现在,我试图验证我的方法是否为4阶。要做到此,而不是绘制误差vs n,我需要绘制n vs n ^(-4)来表明两者具有相同的斜率。

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()

这会导致我的错误图:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以通过再次调用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)。