# 求差商
def Difference(x , y):
# Python二维数组初始化
temp = [[0 for col in range(len(x))] for row in range(len(y))]
for i in range(len(y)):
temp[i][0] = y[i]
result = [y[0]]
# 差商表
for col in range(1,len(y)):
for row in range(col,len(y)):
# 这里的col既代表列数,也代表几阶差商
degree = col
temp[row][col] = (temp[row-1][col-1]-temp[row][col-1])/(x[row-degree]-x[row])
if row == col:
result.append(temp[row][col])
return result
# 牛顿插值
def Newton (result, x, y, In):
temp = [1]
t = 1
sum = temp[0]*result[0]
for i in range(1, len(result)):
for j in range(i):
t *= (In - x[j])
temp.append(t)
sum += temp[i] * result[i]
# 这里t要重置为1
t = 1
return sum
x = [0.40,0.55,0.65,0.80,0.90]
y = [0.41075,0.57815,0.69675,0.88811,1.02652]
# 求各阶差商
result = Difference(x, y)
In = float(input())
# 求牛顿插值结果
print(format(Newton(result,x,y,In), '.3f'))
Python实现牛顿插值
最新推荐文章于 2023-08-21 15:56:51 发布