不多话。
Nowton插值多项式(非等距节点)代码:
1 # -*- coding: utf-8 -*-
2 """
3 Created on Wed Mar 25 15:43:42 2020
4
5 @author: 35035
6 """
7
8
9 import numpy as np
10
11 # Newton插值多项式
12 def Newton_iplt(x, y, xi):
13 """x,y是插值节点array,xi是一个值"""
14
15 n = len(x)
16 m = len(y)
17 if n != m:
18 print('Error!')
19 return None
20 # 先计算差商表(cs)
21 cs = []
22 temp = y.copy()
23 for i in range(n):
24 for j in range(i, n):
25 if i != 0:
26 temp[j] = (temp[j] - temp[j - 1]) / (x[j] - x[j - i])
27 cs.append(temp[i])
28 # 再计算Newton插值
29 ans = 0
30 for i in range(n):
31 w = 1
32 # 计算多项式部分,让差商表作为其系数
33 for j in range(i):
34 w *= (xi - x[j])
35 ans += w*cs[i]
36 return ans
37
38 # 当对多个值使用Lagrange插值时,使用map()建立映射:
39 # Iterator = map(Lagrange, Iterable)
40
41 # 数值运算时使用float参与运算,dtype定为内置float
42 x = np.array((100, 121), dtype = float)
43 y = np.array((10, 11), dtype = float)
44 print(Newton_iplt(x, y, 115))
45 # 测试成功!
在Nowton插值多项式中,差商表的计算至关重要,而对于等距节点的Newton插值,则转为计算差分表。