计算方法-拉格朗日插值法实现函数拟合

拉格朗日插值法实现函数拟合
不多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)

你可能感兴趣的:(一个津门带学生的计算机学习旅程,python,数据分析,线性代数)