curve_fit拟合高斯函数
时间: 2024-05-21 13:16:40 浏览: 58
使用 `curve_fit` 可以拟合高斯函数,具体步骤如下:
1. 导入需要的库
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
```
2. 定义高斯函数
```python
def gaussian(x, a, b, c):
return a * np.exp(-(x - b) ** 2 / (2 * c ** 2))
```
其中,`a`、`b`、`c` 分别是高斯函数的振幅、均值和标准差。
3. 生成样本数据
```python
x = np.linspace(-5, 5, 101)
y = gaussian(x, 1, 0, 1) + 0.2 * np.random.randn(len(x))
```
其中,`x` 是自变量,`y` 是因变量。这里生成了一个带有噪声的高斯函数。
4. 使用 `curve_fit` 进行拟合
```python
popt, pcov = curve_fit(gaussian, x, y)
```
其中,`popt` 是拟合出来的参数值,`pcov` 是协方差矩阵。
5. 绘制拟合结果
```python
plt.plot(x, y, 'b.', label='data')
plt.plot(x, gaussian(x, *popt), 'r-', label='fit')
plt.legend()
plt.show()
```
效果如下图所示:

可以看到,拟合结果很好地还原了原始高斯函数。
阅读全文
相关推荐


















