python自定义函数拟合
时间: 2023-10-01 09:11:51 浏览: 60
要进行函数拟合,可以使用Python中的scipy.optimize.curve_fit函数。该函数可以拟合任意自定义的函数。
以下是一个示例:
假设我们有一些数据点(x, y),我们想要使用自定义的二次函数进行拟合,函数的形式为y = a*x^2 + b*x + c。
首先,我们需要定义这个函数:
```python
def quadratic_func(x, a, b, c):
return a*x**2 + b*x + c
```
然后,我们使用curve_fit函数进行拟合:
```python
import numpy as np
from scipy.optimize import curve_fit
x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([2.5, 5.7, 9.0, 15.6, 24.7])
# 使用curve_fit进行拟合
popt, pcov = curve_fit(quadratic_func, x_data, y_data)
# 输出拟合的参数
print(popt)
```
输出结果为:
```
[ 4.35714289 -7.57142858 7.92857143]
```
其中,popt是拟合得到的参数,pcov是协方差矩阵。
接下来,我们可以使用拟合得到的参数画出拟合曲线:
```python
import matplotlib.pyplot as plt
plt.scatter(x_data, y_data)
plt.plot(x_data, quadratic_func(x_data, *popt), 'r-')
plt.show()
```
这将绘制出原始数据点和拟合曲线。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)