具体代码见我的下载。
"""
拉格朗日插值法
"""
import numpy as np
from sympy.abc import x,y,z
# 插值节点
nodes = [(0.0, 0.0),\
(0.5, 1.6),\
(1.0, 2.0),\
(6.0, 1.5),\
(7.0, 1.5),\
(9.0, 0.0)] # (x, y)
#
def lagrange(cond):
"""
拉格朗日插值法
"""
# Part-1 : 求拉格朗日插值基函数
base_funcs = []
for i in range(len(cond)):
base_func = 1
den = 1 # 分子
num = 1 # 分母
for j in range(len(cond)):
if i != j:
den = den * (x-cond[j][0])
num = num * (cond[i][0]-cond[j][0])
base_func = den / num
base_funcs.append(base_func)
# Part-2 : 求拉格朗日插值函数
f = 0
for i in range(len(cond)):
f = f + cond[i][1]*base_funcs[i]
# Part-3 返回多项式函数
return f, base_funcs
def main():
"""
main函数
"""
# Part-1 : 插值多项式
f, base_funcs = lagrange(nodes)
# Part-2 : 打印输出
print('*'*25,'基函数','*'*25)
counter = 0
for base_func in base_funcs:
print('# L',counter,':' ,base_func)
counter += 1
print('*'*25,'插值多项式','*'*25)
print('# f(x) = ', f)
print('Please press any keys to exit...')
if __name__ == "__main__":
main()