import numpy as np
import matplotlib.pyplot as plt
X = input("x的值:").split(' ')
Y = input("y的值:").split(' ')
x = input("要預(yù)測的值:")
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)
# 原函數(shù)
def fun(x):
return np.sin(x)
# 累乘函數(shù)
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
# 插值基函數(shù)
def P(i, x, X, Y):
P_i = T(x, i, X)/T(X[i], i, X) * Y[i]
return P_i
# 計算預(yù)測值
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("預(yù)測結(jié)果:" + 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()