本文实例为大家分享了python实现拉格朗日插值及作图,供大家参考,具体内容如下
python代码
import numpy as np
import matplotlib.pyplot as plt
X = input("x的值:").split(' ')
Y = input("y的值:").split(' ')
x = input("要预测的值:")
print('\n')
X = np.array(X).astype(np.float64)
Y = np.array(Y).astype(np.float64)
x = np.array(x).astype(np.float64)
n = len(X)
# 原函数
def fun(x):
return np.sin(x)
# 累乘函数
def T(x, i, X):
T_i = 1
for x_i in X:
if X[i] == x_i:
continue
T_i = T_i * (x-x_i)
return T_i
# 插值基函数
def P(i, x, X, Y):
P_i = T(x, i, X)/T(X[i], i, X) * Y[i]
return P_i
# 计算预测值
def L(x, X, Y):
result = 0
for i in range(n):
result = result + P(i, x, X, Y)
return result
y = L(x, X, Y)
print("预测结果:" + str(y) + '\n')
print("误差:" + str(fun(x) - y))
# 画图
X_n = np.linspace(0, 1, 50)
Y_n = fun(X_n)
x_n = np.linspace(0, 1, 50)
y_n = L(x_n, X, Y)
l1, = plt.plot(X_n, Y_n, label='theory')
l2, = plt.plot(x_n, y_n, label='prediction',linestyle='--')
plt.legend(handles=[l1,l2,],labels=['theory','prediction'], loc='best')
plt.show()
代码测试结果(输入方式如图所示):
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。