Files
CalWay_Python/69-3.py
2025-04-16 21:40:31 +08:00

72 lines
2.2 KiB
Python

import math
list_x = [0.0,0.2,0.4,0.6,0.8]
list_y = [1.0,1.2214,1.4918,1.8221,2.2255]
# 定义原函数和其导函数计算结果
def FxDiff_n(x,n):
return math.exp(x)
# 求差分表
def GetDyList(list_y):
result = []
result.append(list_y)
for i in range(len(list_y)-1,0,-1):
tmp = []
for j in range(i):
tmp.append(result[len(list_y)-1-i][j+1] - result[len(list_y)-1-i][j])
result.append(tmp)
return result
# 牛顿前插余项计算
def NewtonForwardRegression(x,n,list_x):
h = list_x[1] - list_x[0]
t = (x - list_x[0]) / h
ks = max([abs(FxDiff_n(list_x[i],n+1)) for i in range(n+1)])
result = 1
for i in range(n+1):
result *= (t-i)*h/(i+1)
return result * ks
# 牛顿前插
def NewtonForwardInterpolation(x,n,list_x,list_y):
list_dyk = GetDyList(list_y)
h = list_x[1] - list_x[0]
t = (x - list_x[0]) / h
result = list_y[0]
mul = 1
result = list_y[0]
for i in range(1, n):
mul *= ((t-i+1)/i)
result += list_dyk[i][0] * mul
r = abs(NewtonForwardRegression(x,n,list_x))
return (result,r)
# 求差商表
def GetDQyList(list_x,list_y):
result = []
result.append(list_y)
for i in range(len(list_y)-1,0,-1):
tmp = []
for j in range(i):
tmp.append((result[len(list_y)-1-i][j+1] - result[len(list_y)-1-i][j])/(list_x[j+len(list_y)-i] - list_x[j]))
result.append(tmp)
return result
# 牛顿基本插值
def NewtonBaseInterpolation(x,n,list_x,list_y):
list_dqy = GetDQyList(list_x,list_y)
result = list_dqy[0][0]
mul = 1
for i in range(1,n):
mul *= (x - list_x[i-1])
result += list_dqy[i][0] * mul
return result
if __name__ == '__main__':
print("三点牛顿前插 e^0.12 结果为%f, 截断误差%f" % NewtonForwardInterpolation(0.12, 2, list_x, list_y))
print("四点牛顿前插 e^0.12 结果为%f, 截断误差%f" % NewtonForwardInterpolation(0.12, 3, list_x, list_y))
print("三点牛顿基本插值 e^0.12 结果为%f" % NewtonBaseInterpolation(0.12, 2, list_x, list_y))
print("四点牛顿基本插值 e^0.12 结果为%f" % NewtonBaseInterpolation(0.12, 3, list_x, list_y))