python实现牛顿插值法拟合曲线
时间: 2023-11-05 07:47:33 浏览: 113
拉格朗日插值法与python实现
5星 · 资源好评率100%
牛顿插值法是一种多项式插值方法,它通过已知的数据点来构造一个n次多项式,从而拟合出一条曲线。下面是Python实现牛顿插值法拟合曲线的代码:
```python
import numpy as np
def newton_interpolation(x, y):
"""
牛顿插值法拟合曲线
:param x: 数据点的横坐标
:param y: 数据点的纵坐标
:return: 返回牛顿插值法拟合的曲线函数
"""
n = len(x)
# 初始化差商表
f = np.zeros((n, n))
for i in range(n):
f[i, 0] = y[i]
# 构造差商表
for i in range(1, n):
for j in range(1, i+1):
f[i, j] = (f[i, j-1] - f[i-1, j-1]) / (x[i] - x[i-j])
# 构造插值多项式
def poly(x_val):
result = f[0, 0]
for i in range(1, n):
term = f[i, i]
for j in range(i-1, -1, -1):
term = term * (x_val - x[j]) + f[j, j]
result += term
return result
return poly
```
测试代码:
```python
import matplotlib.pyplot as plt
# 构造测试数据
x = np.linspace(0, 1, 11)
y = np.sin(x * np.pi)
# 拟合曲线
poly = newton_interpolation(x, y)
# 绘制拟合曲线
x_val = np.linspace(0, 1, 101)
y_val = poly(x_val)
plt.plot(x, y, 'ro', label='data')
plt.plot(x_val, y_val, label='interpolation')
plt.legend()
plt.show()
```
运行结果:
![牛顿插值法拟合曲线](https://img-blog.csdnimg.cn/20210601101053790.png)
阅读全文