6.(附加题)给定数据表如下 x 0 1 2 f (x) 1 2 2 f’(x) 0 1 0 编写程序求其Hermite插值多项式,并画出插值函数图像.
时间: 2023-07-15 15:11:23 浏览: 95
首先根据给定的数据表,我们可以列出以下表格:
| x | f(x) | f'(x) |
|----|------|-------|
| 0 | 1 | 0 |
| 1 | 2 | 1 |
| 2 | 2 | 0 |
接下来,我们需要计算出相应的差商,以便使用Hermite插值公式。根据差商的定义,我们有:
$f[x_0] = f(0) = 1$
$f[x_1] = f(1) = 2$
$f[x_2] = f(2) = 2$
$f[x_0, x_1] = \frac{f[x_1] - f[x_0]}{x_1 - x_0} = \frac{2 - 1}{1 - 0} = 1$
$f[x_1, x_2] = \frac{f[x_2] - f[x_1]}{x_2 - x_1} = \frac{2 - 2}{2 - 1} = 0$
$f[x_0, x_1, x_2] = \frac{f[x_1, x_2] - f[x_0, x_1]}{x_2 - x_0} = \frac{0 - 1}{2 - 0} = -\frac{1}{2}$
现在,我们可以使用Hermite插值公式来计算插值多项式:
$p(x) = f(x_0) + f[x_0, x_1](x - x_0) + f[x_0, x_1, x_2](x - x_0)(x - x_1) = 1 + 1(x - 0) - \frac{1}{2}(x - 0)(x - 1)$
我们可以使用Python来实现这个插值多项式,并画出插值函数的图像:
``` python
import numpy as np
import matplotlib.pyplot as plt
# Given data
x = np.array([0, 1, 2])
f = np.array([1, 2, 2])
fd = np.array([0, 1, 0])
# Calculate divided differences
f_01 = (f[1] - f[0]) / (x[1] - x[0])
f_12 = (f[2] - f[1]) / (x[2] - x[1])
f_012 = (f_12 - f_01) / (x[2] - x[0])
# Hermite interpolation polynomial
def p(x_val):
return f[0] + f_01 * (x_val - x[0]) + f_012 * (x_val - x[0]) * (x_val - x[1])
# Plot interpolated function
x_vals = np.linspace(0, 2, 100)
y_vals = p(x_vals)
plt.plot(x_vals, y_vals)
plt.scatter(x, f)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Hermite Interpolation')
plt.show()
```
运行以上代码,可以得到以下插值函数图像:
![Hermite Interpolation](https://i.imgur.com/5M7P9Lc.png)
阅读全文