# # 方法一 导包的方法
# from scipy.interpolate import lagrange
#
# x = [1, 3, 5]
# y = [2, 10, 1]
# print(lagrange(x, y))
# print(lagrange(x, y)(10))
import numpy
import matplotlib
from matplotlib import pyplot
# 手撸代码
x = [1, 3, 5]
y = [2, 10, 1]
def lagrange_interpolate(x1):
P = []
L_n = 0
# for循环计算每一个基函数 并将每个基函数存入list列表中
for i in range(len(x)):
fenzi = 1
fenmu = 1
for j in range(len(x)):
if j != i:
fenzi *= (x1 - x[j])
fenmu *= (x[i] - x[j])
P.append(fenzi / fenmu)
#L_n存入每个点的结果
for i in range(len(x)):
L_n += y[i] * P[i]
return round(L_n, 3)
x2 = numpy.linspace(-10, 10, 20, endpoint=False)
y2 = []
for i in range(len(x2)):
y2.append(lagrange_interpolate(x2[i]))
pyplot.plot(x2, y2)
pyplot.scatter(x, y, marker='.')
pyplot.show()
拉格朗日插值法及python实现
最新推荐文章于 2023-10-10 00:14:22 发布