python拟合曲线得到函数
时间: 2023-10-13 08:15:20 浏览: 52
在Python中,可以使用SciPy库中的curve_fit函数来拟合曲线并得到函数。
首先导入必要的库:
```python
import numpy as np
from scipy.optimize import curve_fit
```
然后定义要拟合的函数,例如:
```python
def func(x, a, b, c):
return a * np.exp(-b * x) + c
```
其中x是自变量,a、b、c是拟合的参数。
接着准备好数据,例如:
```python
xdata = np.linspace(0, 4, 50)
ydata = func(xdata, 2.5, 1.3, 0.5)
```
这里使用linspace函数生成了50个在0到4之间的数作为x,同时使用上面定义的函数生成对应的y。
然后使用curve_fit函数拟合曲线:
```python
popt, pcov = curve_fit(func, xdata, ydata)
```
其中popt就是拟合得到的参数,pcov是协方差矩阵。
最后可以打印出拟合得到的函数:
```python
print('拟合函数:y = %f * exp(-%f * x) + %f' % tuple(popt))
```
完整的代码如下:
```python
import numpy as np
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
xdata = np.linspace(0, 4, 50)
ydata = func(xdata, 2.5, 1.3, 0.5)
popt, pcov = curve_fit(func, xdata, ydata)
print('拟合函数:y = %f * exp(-%f * x) + %f' % tuple(popt))
```
输出:
```
拟合函数:y = 2.500000 * exp(-1.300000 * x) + 0.500000
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)