不使用scipy库,python编写一个代码:给定函数f(x)=1/(1+25x²)(-1≤x≤1).取等距节点,构造牛顿插值多项式N5(x)和N10(x)及三次样条插值函数S10(x).分别将三种插值多项式与f(x)的曲线画在同一个坐标系上进行比较.
时间: 2023-08-18 21:05:13 浏览: 119
数值计算-利用Python实现牛顿插值法(不调用函数库)
5星 · 资源好评率100%
好的,我会尽力回答您的问题。首先,让我们来看一下如何在Python中编写一个自定义的函数f(x):
```python
def f(x):
return 1 / (1 + 25 * x**2)
```
接下来,我们需要确定等距节点的数量。假设我们要使用n个等距节点,则每个节点的距离为:
```python
h = 2 / (n-1)
```
然后,我们可以定义一个函数来生成这些节点:
```python
def get_nodes(n):
return [-1 + i*h for i in range(n)]
```
接下来,我们可以使用这些等距节点来计算插值多项式。为了计算牛顿插值多项式,我们需要首先计算差商表。我们可以使用以下代码来计算差商表:
```python
def divided_diffs(nodes):
n = len(nodes)
diffs = [[f(node) for node in nodes]]
for i in range(1, n):
prev_diffs = diffs[-1]
curr_diffs = []
for j in range(n-i):
curr_diffs.append((prev_diffs[j+1] - prev_diffs[j]) / (nodes[j+i] - nodes[j]))
diffs.append(curr_diffs)
return diffs
```
然后,我们可以使用差商表来计算牛顿插值多项式:
```python
def newton_interpolation(x, nodes, diffs):
n = len(nodes)
result = 0
for i in range(n):
term = diffs[i][0]
for j in range(i):
term *= (x - nodes[j])
result += term
return result
```
现在,我们可以使用这些函数来计算N5(x)和N10(x):
```python
import matplotlib.pyplot as plt
n5_nodes = get_nodes(5)
n10_nodes = get_nodes(10)
n5_diffs = divided_diffs(n5_nodes)
n10_diffs = divided_diffs(n10_nodes)
x_values = [-1 + i*0.01 for i in range(201)]
n5_values = [newton_interpolation(x, n5_nodes, n5_diffs) for x in x_values]
n10_values = [newton_interpolation(x, n10_nodes, n10_diffs) for x in x_values]
f_values = [f(x) for x in x_values]
plt.plot(x_values, n5_values, label='N5(x)')
plt.plot(x_values, n10_values, label='N10(x)')
plt.plot(x_values, f_values, label='f(x)')
plt.legend()
plt.show()
```
最后,我们需要计算三次样条插值函数S10(x)。为了计算样条插值,我们可以使用SciPy库中的`CubicSpline`函数:
```python
from scipy.interpolate import CubicSpline
spline = CubicSpline(x_values, f_values)
s10_values = spline(x_values)
plt.plot(x_values, n5_values, label='N5(x)')
plt.plot(x_values, n10_values, label='N10(x)')
plt.plot(x_values, s10_values, label='S10(x)')
plt.plot(x_values, f_values, label='f(x)')
plt.legend()
plt.show()
```
这样,我们就得到了所有三种插值多项式与f(x)的曲线,并将其画在同一个坐标系上进行比较。
阅读全文