插值方法 - Newton多项式(非等距节点)

不多话。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         if i != 0:
25             iv_1 = temp[i - 1]
26             for j in range(i, n):
27                 iv_2 = temp[j]
28                 temp[j] = (iv_2 - iv_1) / (x[j] - x[j - i])
29                 iv_1 = iv_2
30         cs.append(temp[i])
31     # 再计算Newton插值
32     ans = 0
33     for i in range(n):
34         w = 1   
35         # 计算多项式部分,让差商表作为其系数
36         for j in range(i):
37             w *= (xi - x[j])
38         ans += w*cs[i]
39     return ans
40 
41 # 当对多个值使用Newton插值时,使用map()建立映射:
42 # Iterator = map(Newton, Iterable)
43 
44 # 数值运算时使用float参与运算,dtype定为内置float
45 
46 x = np.array((100, 121), dtype = float)
47 y = np.array((10, 11), dtype = float)
48 print(Newton_iplt(x, y, 115))
49 
50 x = np.array((1,2,3,4,5,6), dtype=float)
51 y = np.array((1.0, 1.2599, 1.4422, 1.5874, 1.71, 1.8171), dtype=float)
52 print(Newton_iplt(x, y, 5.6))
53 # 结果:10.71428  1.7754  测试成功!

在Nowton插值多项式中,差商表的计算至关重要,而对于等距节点的Newton插值,则转为计算差分表。

posted on 2020-03-26 02:16  Black_x  阅读(793)  评论(0编辑  收藏  举报