一次和二次lagrange插值多项式的程序
时间: 2024-09-18 13:16:23 浏览: 48
Lagrange插值法是一种数学上用于构建函数近似的技术,特别是在数据采样点之间寻找一条通过这些点的线性或更高次的多项式。这里简单讲解一下如何编写一个Python程序实现一次和二次拉格朗日插值:
**一次拉格朗日插值** (Linear Lagrange Interpolation):
```python
def linear_interpolation(x_values, y_values, x_query):
n = len(x_values)
if n != len(y_values):
raise ValueError("Length of x and y values should be the same.")
interpolation = 0
for i in range(n):
l_i = 1
for j in range(n):
if i == j:
continue
l_i *= (x_query - x_values[j]) / (x_values[i] - x_values[j])
interpolation += y_values[i] * l_i
return interpolation
# 使用示例
x_data = [0, 1, 2]
y_data = [1, 4, 9]
x_to_find = 1.5
print(linear_interpolation(x_data, y_data, x_to_find))
```
**二次拉格朗日插值** (Quadratic Lagrange Interpolation) 更复杂一些,涉及计算三次多项式系数:
```python
from numpy import polyval, zeros
def quadratic_interpolation(x_values, y_values, x_query):
n = len(x_values)
if n < 3:
raise ValueError("At least three points are required for quadratic interpolation.")
# 计算拉格朗日基本多项式
basis_polys = [[(x - x_j) for x_j in x_values if x_i != x_j] for x_i in x_values]
# 系数矩阵 A 和 Y 向量
A = zeros((n, n))
Y = zeros(n)
for i in range(n):
for j in range(n):
if i != j:
A[i, j] = basis_polys[i][j]
Y[i] = y_values[i]
# 解决线性方程组得到插值多项式系数
coeffs = np.linalg.solve(A, Y)
# 返回插值结果
return polyval(coeffs, x_query)
# 示例
x_data = [0, 1, 2, 3]
y_data = [0, 1, 4, 9]
x_to_find = 1.75
print(quadratic_interpolation(x_data, y_data, x_to_find))
```
阅读全文