python實現拉格朗日插值及作圖

本文實例為大傢分享瞭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()

代碼測試結果(輸入方式如圖所示):

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。