拉格朗日插值,分段线性插值,三次样条插值代码实现
时间: 2024-03-23 19:39:47 浏览: 73
三次样条插值算法,能够实现数据的分段插值,拟合精度较高,曲线也比较光滑
以下是Python代码实现:
1. 拉格朗日插值
```python
import numpy as np
def lagrange_interp(x, y, x_interp):
n = len(x)
y_interp = np.zeros(len(x_interp))
for i in range(n):
p = 1
for j in range(n):
if i != j:
p *= (x_interp - x[j]) / (x[i] - x[j])
y_interp += y[i] * p
return y_interp
```
2. 分段线性插值
```python
import numpy as np
def linear_interp(x, y, x_interp):
n = len(x)
y_interp = np.zeros(len(x_interp))
for i in range(len(x_interp)):
for j in range(n-1):
if x_interp[i] >= x[j] and x_interp[i] <= x[j+1]:
y_interp[i] = y[j] + (y[j+1] - y[j]) / (x[j+1] - x[j]) * (x_interp[i] - x[j])
break
return y_interp
```
3. 三次样条插值
```python
import numpy as np
from scipy.interpolate import CubicSpline
def cspline_interp(x, y, x_interp):
cs = CubicSpline(x, y)
y_interp = cs(x_interp)
return y_interp
```
以上三种插值方法均可根据给定的输入数据进行插值计算。需要注意的是,对于分段线性插值,x 必须是单调递增的。而对于三次样条插值,x 可以是任意顺序的。
阅读全文