Python中的拉格朗日插值 - 不会打印出来

时间:2016-11-07 16:59:46

标签: python interpolation polynomials

这是我必须解决的问题:

编写一个程序来评估和绘制u(x)= 1 /(1 + x ^ 2)的拉格朗日插值Iu(x),其中x在-5和5之间。为5,7,9,11执行此操作,13,15点插值(5,7,9等数据点之间,包括-5和5)。您的结果应显示函数和插值。

这是我到目前为止提出的代码:

import numpy as np
import matplotlib.pyplot as plt


def L_k(x, k, xp, yp):
    ans = 1
    for i in range(len(xp)):
        if i != k:
        ans *= (x - xp[i]) / (xp[k] - xp[i])
    return ans


def p_L(x, xp, yp):
    ans = 0
    for k in range(len(yp)):
        ans += yp[k] * L_k(x, k, xp, yp)
    return ans


def verify(xp, yp):
    status = 'Verified!'
    for k in range(len(xp)):
        if abs(p_L(xp[k], xp, yp) - yp[k]) > 1e-15:
            status = 'Error!'
            break
    print (status)


def verbose_verify(xp, yp):
    print  ('x', 'Exact', 'Approx', 'Difference')
    for k in range(len(xp)):
        x = xp[k]
        exact = yp[k]
        approx = p_L(xp[k], xp, yp)
        diff = abs(p_L(xp[k], xp, yp) - yp[k])
        print (x, exact, approx, diff)


def graph(f, n, xmin, xmax, resolution=1001):
    xlist = np.linspace(xmin, xmax, n)
    ylist = f(xlist)
    xlist_fine = np.linspace(xmin, xmax, resolution)
    ylist_fine = p_L(xlist_fine, xlist, ylist)
    plt.plot(xlist, ylist, 'ro')
    plt.plot(xlist_fine, ylist_fine)


def annotate_graph():
    ax = plt.gca()
    ax.set_xlabel('x')
    ax.set_ylabel('f(x)')
    ax.legend(['f(x)', 'Interpolated'])

if __name__ == '__main__':
    xlist = np.linspace(0, np.pi, 5)
    ylist = np.sin(xlist)
    verbose_verify(xlist, ylist)
    graph(np.sin, 5, 0, np.pi)
    annotate_graph()
    plt.show()

然而,它没有打印任何东西。没有错误出现,没有输出。我做错了什么?

0 个答案:

没有答案