拉格朗日插值法實現函數擬合
不多BB,直接上代碼
'''
@Author: your name
@Date: 2020-03-18 14:53:28
@LastEditTime: 2020-03-19 01:01:10
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: \計算作業\測試.py
'''
import matplotlib.pyplot as plt
import numpy as np
from sympy import *
xpoint=[-1,0,1,2]
ypoint=[15,5,1,-3]
# coefficient = []
# polynomial = []
subitem=[]
answer=[]
y = Symbol("y")
def Lagrange(y):
for j in xpoint:
val = coe = 1
for i in xpoint:
if i == j:
continue
else:
key = j-i
val *= key
term = y-i
coe *= term
subitem.append(round(1/val,5)*coe)
# polynomial.append(coe)
# coefficient.append(round(1/val,5))
count = 0
for n in range(0,len(ypoint)):
a=ypoint[n]*subitem[n]
print(a)
answer.append(a)
num=0
for n in answer:
num+=n
return num
plt.xlim((-2, 2))
plt.ylim((-5, 15))
y = np.arange(-2.5, 2.5, 0.1)
plt.scatter(xpoint, ypoint, marker='o', color='black', s=40, label='已知散點')
plt.plot(y, Lagrange(y), color='red', linewidth=2.0, linestyle='-', label='導數')
plt.show()
#print(subitem)
# print(polynomial)
# print(coefficient)