python 非线性曲线拟合代码
时间: 2024-06-11 11:01:50 浏览: 22
Python 中有多种实现非线性曲线拟合的方法,比如最小二乘法、Levenberg-Marquardt 算法、拟合平滑曲线等。其中,最常用的非线性曲线拟合库是 SciPy 中的 optimize 模块。
以下是一个使用 SciPy 实现非线性曲线拟合的代码示例:
```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)
y_noise = 0.2 * np.random.normal(size=xdata.size)
ydata = ydata + y_noise
# 使用 curve_fit 进行拟合
popt, pcov = curve_fit(func, xdata, ydata)
# 输出拟合结果
print(popt)
# 绘制拟合曲线
import matplotlib.pyplot as plt
plt.figure()
plt.plot(xdata, ydata, 'b-', label='data')
plt.plot(xdata, func(xdata, *popt), 'r-', label='fit')
plt.legend()
plt.show()
```
在这个例子中,我们使用了 `curve_fit` 函数来进行非线性曲线拟合。这个函数需要传入两个参数,第一个是要拟合的函数,第二个是 x 和 y 的数据。
输出结果中的 `popt` 变量即为拟合结果,它是一个包含三个元素的数组,分别对应着函数中的三个参数 a、b 和 c。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_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)