最小二乘法的python插值代码
时间: 2023-12-20 20:29:40 浏览: 79
以下是使用最小二乘法进行插值的Python代码示例:
```python
import numpy as np
# 定义最小二乘法函数
def least_squares(x, y, n):
x_matrix = np.mat([[i**j for j in range(n+1)] for i in x])
y_matrix = np.mat(y).T
xTx = x_matrix.T * x_matrix
if np.linalg.det(xTx) == 0.0:
print("This matrix is singular, cannot do inverse")
return
w = xTx.I * (x_matrix.T * y_matrix)
return w
# 定义插值函数
def interpolate(x, y, n, x_new):
w = least_squares(x, y, n)
x_new_matrix = np.mat([[i**j for j in range(n+1)] for i in x_new])
y_new_matrix = x_new_matrix * w
y_new = [y_new_matrix[i, 0] for i in range(len(x_new))]
return y_new
# 示例
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
n = 2 # 二次插值
x_new = [1.5, 2.5, 3.5, 4.5]
y_new = interpolate(x, y, n, x_new)
print(y_new) # 输出:[2.25, 6.25, 12.25, 20.25]
```
阅读全文