编写Lagrange插值、Newton插值及分段线性插值多项式的程序,对函数f(x)=1/(1+x^2 )在[-5,5]上进行插值,并分别绘制插值函数及f(x)的图形,比较分析。N分别取5、10、20、40。
时间: 2024-10-10 19:10:36 浏览: 70
Lagrange_Newton_Aitken插值算法.rar_Aitken_aitken插值_lagrange_newton_插
Lagrange插值、Newton插值以及分段线性插值都是数值计算中常用的逼近函数的方法。下面是一个简化的Python程序示例,使用numpy库来实现这些插值算法,并使用matplotlib绘制插值结果:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义原始函数 f(x)
def f(x):
return 1 / (1 + x**2)
# 插值方法
methods = ['lagrange', 'newton', 'piecewise_linear']
x_values = np.linspace(-5, 5, N for N in [5, 10, 20, 40])
y_values = f(x_values)
# 函数定义
def lagrange_interpolation(x, y, N):
xi = np.zeros(N+1)
yi = np.zeros(N+1)
return np.polyval(np.vander(xi, N+1) @ np.linalg.inv(np.vander(xi, N+2)) @ yi, x)
def newton_interpolation(x, y, N):
coefficients = np.zeros(N+1)
for i in range(N+1):
coefficients[i] = np.sum(y[:-i] * x**(i+1)) / (i+1)
return np.polyval(coefficients, x)
def piecewise_linear_interpolation(x_values, y_values):
intervals = np.diff(x_values).tolist() + [np.inf]
interp = []
for i in range(len(intervals)):
left, right = x_values[i], x_values[i+1] if i < len(intervals)-1 else np.inf
slope = (y_values[i+1] - y_values[i]) / (right - left)
intercept = y_values[i] - slope * left
interp.append(lambda x: slope * (x - left) + intercept if left <= x <= right else None)
return interp
# 绘制插值函数和原函数图
fig, axs = plt.subplots(3, len(methods), figsize=(10, 8))
for ax, method in zip(axs.flatten(), methods):
if method == 'lagrange':
interp_y = [lagrange_interpolation(x, y_values[n*N:(n+1)*N], n) for n in range(len(x_values)//N)]
elif method == 'newton':
interp_y = [newton_interpolation(x, y_values[n*N:(n+1)*N], n) for n in range(len(x_values)//N)]
else: # piecewise_linear
interp_y = piecewise_linear_interpolation(x_values, y_values)
ax.plot(x_values, f(x_values), label='Original Function')
for i, interp in enumerate(interp_y):
if interp is not None:
ax.plot(x_values, interp(x_values), label=f'{method} ({N})' if i == 0 else '')
ax.set_title(method)
ax.legend()
plt.tight_layout()
# 显示图形
plt.show()
```
这个程序首先定义了函数f(x),然后实现了三种插值方法的函数。接着对给定的区间[-5, 5]和不同的N值进行插值,并将插值结果和原函数一起画出。每个子图会展示每种方法在不同N值下的插值效果。
阅读全文