首先采用拉格朗日插值方法实现函数内新增 50 个等间距样本点的内插,随后采用函数y=f(x),对所给数据分别进 行线性拟合和非线性拟合数值计算。
时间: 2024-03-12 13:47:53 浏览: 64
首先,我们需要定义原始数据的函数$f(x)$,并生成一些初始数据。
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义原始函数
def f(x):
return np.sin(x)
# 生成初始数据
x_data = np.linspace(0, 2*np.pi, 10)
y_data = f(x_data)
```
接下来,我们使用拉格朗日插值方法在原始数据的基础上新增50个等间距样本点。这里,我们使用`numpy.interp`函数来实现插值。
```python
# 新增50个等间距样本点
x_interp = np.linspace(0, 2*np.pi, 60)
y_interp = np.interp(x_interp, x_data, y_data)
```
现在,我们有了60个样本点,可以对这些样本点进行线性拟合和非线性拟合。
首先,我们来进行线性拟合。我们可以使用`numpy.polyfit`函数来进行多项式拟合。在这里,我们选择一次多项式进行拟合,即线性拟合。
```python
# 线性拟合
p_linear = np.polyfit(x_interp, y_interp, 1)
# 绘制拟合结果
plt.plot(x_interp, y_interp, 'o', label='data')
plt.plot(x_interp, np.polyval(p_linear, x_interp), '-', label='linear fit')
plt.legend()
plt.show()
```
接下来,我们进行非线性拟合。我们可以使用`scipy.optimize.curve_fit`函数来拟合自定义的非线性模型函数。在这里,我们选择一个二次函数作为非线性模型函数。
```python
from scipy.optimize import curve_fit
# 定义非线性模型函数
def model_func(x, a, b, c):
return a * x**2 + b * x + c
# 非线性拟合
p_nonlinear, _ = curve_fit(model_func, x_interp, y_interp)
# 绘制拟合结果
plt.plot(x_interp, y_interp, 'o', label='data')
plt.plot(x_interp, model_func(x_interp, *p_nonlinear), '-', label='nonlinear fit')
plt.legend()
plt.show()
```
在上面的代码中,我们首先定义了一个二次函数作为非线性模型函数,并使用`curve_fit`函数对数据进行拟合。最后,我们绘制了拟合结果。
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# 定义原始函数
def f(x):
return np.sin(x)
# 生成初始数据
x_data = np.linspace(0, 2*np.pi, 10)
y_data = f(x_data)
# 新增50个等间距样本点
x_interp = np.linspace(0, 2*np.pi, 60)
y_interp = np.interp(x_interp, x_data, y_data)
# 线性拟合
p_linear = np.polyfit(x_interp, y_interp, 1)
# 非线性模型函数
def model_func(x, a, b, c):
return a * x**2 + b * x + c
# 非线性拟合
p_nonlinear, _ = curve_fit(model_func, x_interp, y_interp)
# 绘制拟合结果
plt.plot(x_interp, y_interp, 'o', label='data')
plt.plot(x_interp, np.polyval(p_linear, x_interp), '-', label='linear fit')
plt.plot(x_interp, model_func(x_interp, *p_nonlinear), '-', label='nonlinear fit')
plt.legend()
plt.show()
```
在上面的代码中,我们绘制了原始数据、线性拟合结果和非线性拟合结果的图像。
阅读全文
相关推荐











