目錄
- 1. n階差商實(shí)現(xiàn)
- 2. 牛頓插值實(shí)現(xiàn)
- 3.完整Python代碼
1. n階差商實(shí)現(xiàn)
def diff(xi,yi,n):
"""
param xi:插值節(jié)點(diǎn)xi
param yi:插值節(jié)點(diǎn)yi
param n: 求幾階差商
return: n階差商
"""
if len(xi) != len(yi): #xi和yi必須保證長度一致
return
else:
diff_quot = [[] for i in range(n)]
for j in range(1,n+1):
if j == 1:
for i in range(n+1-j):
diff_quot[j-1].append((yi[i]-yi[i+1]) / (xi[i] - xi[i + 1]))
else:
for i in range(n+1-j):
diff_quot[j-1].append((diff_quot[j-2][i]-diff_quot[j-2][i+1]) / (xi[i] - xi[i + j]))
return diff_quot
測試一下:
xi = [1.615,1.634,1.702,1.828]
yi = [2.41450,2.46259,2.65271,3.03035]
n = 3
print(diff(xi,yi,n))
返回的差商結(jié)果為:
[[2.53105263157897, 2.7958823529411716, 2.997142857142854], [3.0440197857724347, 1.0374252793901158], [-9.420631485362996]]
2. 牛頓插值實(shí)現(xiàn)
def Newton(x):
f = yi[0]
v = []
r = 1
for i in range(n):
r *= (x - xi[i])
v.append(r)
f += diff_quot[i][0] * v[i]
return f
測試一下:
x = 1.682
print(Newton(x))
結(jié)果為:
2.5944760289639732
3.完整Python代碼
def Newton(xi,yi,n,x):
"""
param xi:插值節(jié)點(diǎn)xi
param yi:插值節(jié)點(diǎn)yi
param n: 求幾階差商
param x: 代求近似值
return: n階差商
"""
if len(xi) != len(yi): #xi和yi必須保證長度一致
return
else:
diff_quot = [[] for i in range(n)]
for j in range(1,n+1):
if j == 1:
for i in range(n+1-j):
diff_quot[j-1].append((yi[i]-yi[i+1]) / (xi[i] - xi[i + 1]))
else:
for i in range(n+1-j):
diff_quot[j-1].append((diff_quot[j-2][i]-diff_quot[j-2][i+1]) / (xi[i] - xi[i + j]))
print(diff_quot)
f = yi[0]
v = []
r = 1
for i in range(n):
r *= (x - xi[i])
v.append(r)
f += diff_quot[i][0] * v[i]
return f
到此這篇關(guān)于用Python實(shí)現(xiàn)牛頓插值法的文章就介紹到這了,更多相關(guān)python牛頓插值法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python+Appium新手教程
- Python requests timeout的設(shè)置
- 在python代碼中加入環(huán)境變量的語句操作
- python matplotlib繪圖實(shí)現(xiàn)刪除重復(fù)冗余圖例的操作
- Python爬蟲之爬取2020女團(tuán)選秀數(shù)據(jù)
- python爬取各省降水量及可視化詳解
- python爬蟲之教你如何爬取地理數(shù)據(jù)
- 用Python的繪圖庫(matplotlib)繪制小波能量譜