python代码 指数函数拟合
时间: 2023-09-12 21:02:49 浏览: 109
可以使用SciPy库中的curve_fit函数进行指数函数拟合,具体步骤如下:
1. 导入必要的库
```
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
```
2. 准备数据
假设我们有一组指数函数形式的数据:
```
x = np.array([1, 2, 3, 4, 5])
y = np.array([0.5, 2.5, 7, 14, 24.5])
```
3. 定义指数函数模型
```
def func(x, a, b, c):
return a * np.exp(-b * x) + c
```
其中,a、b、c为拟合参数。
4. 进行拟合
```
popt, pcov = curve_fit(func, x, y)
```
其中,popt为拟合后得到的参数值,pcov为协方差矩阵。
5. 绘制拟合曲线
```
plt.plot(x, y, 'b-', label='data')
plt.plot(x, func(x, *popt), 'r--', label='fit')
plt.legend()
plt.show()
```
完整代码如下:
```
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5])
y = np.array([0.5, 2.5, 7, 14, 24.5])
def func(x, a, b, c):
return a * np.exp(-b * x) + c
popt, pcov = curve_fit(func, x, y)
plt.plot(x, y, 'b-', label='data')
plt.plot(x, func(x, *popt), 'r--', label='fit')
plt.legend()
plt.show()
```
阅读全文
相关推荐


















