写一个代码,对微分方程组进行未知参数拟合
时间: 2023-09-02 21:13:15 浏览: 42
好的,以下是一个对微分方程组进行未知参数拟合的 Python 代码示例,使用了 Scipy 库中的 curve_fit 方法:
```python
import numpy as np
from scipy.integrate import odeint
from scipy.optimize import curve_fit
# 定义微分方程组
def diff_eqs(y, t, a, b, c):
dydt = [
a * y[0] - b * y[0] * y[1],
c * y[0] * y[1] - b * y[1]
]
return dydt
# 生成数据
t = np.linspace(0, 10, 101)
y0 = [1, 1]
a_true, b_true, c_true = 1, 0.2, 0.1
y_true = odeint(diff_eqs, y0, t, args=(a_true, b_true, c_true))
y_noisy = y_true + 0.05 * np.random.randn(*y_true.shape)
# 定义拟合函数
def fit_func(t, a, b, c):
y_fit = odeint(diff_eqs, y0, t, args=(a, b, c))
return y_fit.ravel()
# 拟合参数
p0 = [2, 1, 1]
popt, pcov = curve_fit(fit_func, t, y_noisy.ravel(), p0=p0)
# 输出拟合结果
a_fit, b_fit, c_fit = popt
print("True parameters: a={}, b={}, c={}".format(a_true, b_true, c_true))
print("Fitted parameters: a={}, b={}, c={}".format(a_fit, b_fit, c_fit))
```
该代码将生成一组带噪声的微分方程组的数据,并使用 Scipy 库中的 curve_fit 方法对数据进行拟合,得到了未知参数的估计值。