用Python实现Newton插值法
程序员文章站
2022-03-21 11:05:37
1. n阶差商实现def diff(xi,yi,n): """ param xi:插值节点xi param yi:插值节点yi param n: 求几阶差商 return...
1. n阶差商实现
def diff(xi,yi,n): """ param xi:插值节点xi param yi:插值节点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))
返回的差商结果为:
[[2.53105263157897, 2.7958823529411716, 2.997142857142854], [3.0440197857724347, 1.0374252793901158], [-9.420631485362996]]
2. 牛顿插值实现
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))
结果为:
2.5944760289639732
完整python代码
def newton(xi,yi,n,x): """ param xi:插值节点xi param yi:插值节点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
到此这篇关于用python实现牛顿插值法的文章就介绍到这了,更多相关python牛顿插值法内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
python使用插值法画出平滑曲线
-
Python实现分段线性插值
-
python实现三次样条插值
-
python利用插值法对折线进行平滑曲线处理
-
作业笔记:基于二次插值的Wolfe-Powell非精确线搜索算法及Python代码实现
-
python用插值法绘制平滑曲线
-
python样条插值的实现代码
-
图像的灰度化处理(Python实现三种方法——最大值法、平均值法、加权均值法、gamma校正)
-
python数据分析与挖掘实战---拉格朗日插值法
-
荐 python 数据、曲线平滑处理——方法总结(Savitzky-Golay 滤波器、make_interp_spline插值法和convolve滑动平均滤波)