python拉格朗日插值及作图 python实现拉格朗日插值及作图
From Star. 人气:0想了解python实现拉格朗日插值及作图的相关内容吗,From Star.在本文为您仔细讲解python拉格朗日插值及作图的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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()
代码测试结果(输入方式如图所示):
加载全部内容