我对拉格朗日多项式的解释和图的构造是否正确?

时间:2016-09-22 08:23:02

标签: python matplotlib

import matplotlib.pyplot as plt
import matplotlib.pyplot as plt


def f(x):
   return (1 + np.exp(-x)) / (1 + x ** 4)
def lagrange(x, y, x0):
   ret = []
   for j in range(len(y)):
       numerator = 1.0
       denominator = 1.0
       for k in range(len(x)):
           if k != j:
               numerator *= (x0 - x[k])
               denominator *= (x[j] - x[k])
       ret.append(y[j] * (numerator / denominator))
   return ret
plt.plot(x, lagrange(x, f(x), 5), label="Polynom")
plt.plot(x, f(x), label="Function")
plt.legend(loc='upper left')
plt.show()

我需要使用原始函数和拉格朗日多项式构建图。我新手到matplotlib库(和一般的python),所以我想确认我是对的

1 个答案:

答案 0 :(得分:0)

SciPy有lagrange,这是一个例子:

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import lagrange

def f(x):
    return (1 + np.exp(-x)) / (1 + x ** 4)
x = np.linspace(-1, 1, 10)
x2 = np.linspace(-1, 1, 100)
y = f(x)
p = lagrange(x, y)
plt.plot(x, f(x), "o", label="Function")
plt.plot(x2, np.polyval(p, x2), label="Polynom")
plt.legend(loc='upper right')

输出:

enter image description here

如果您想通过拉格朗日公式计算插值曲线:

den = x[:, None] - x[None, :]
num = x2[:, None] - x[None, :]

with np.errstate(divide='ignore', invalid='ignore'):
    div = num[:, None, :] / den[None, :, :]

div[~np.isfinite(div)] = 1

y2 = (np.product(div, axis=-1) * y).sum(axis=1)

plt.plot(x, y, "o")
plt.plot(x2, y2)

该代码使用numpy广播来加速计算。