SymPy dsolve无法针对初始条件进行求解
问题描述
我正在尝试用SymPy的dsolve
用ICS解以下微分方程:
from sympy import Function, Derivative, dsolve, symbols
t, k = symbols('t,k', real=True)
M = Function('M')(t)
M_ = Derivative(M,t)
Eqn = M_ - k*M
sol = dsolve(Eqn, ics={M.subs(t,0): 100, M.subs(t, 6): 97})
我收到以下错误:
File "..PythonPython39libsite-packagessympysolversodeode.py", line 826, in solve_ics
raise ValueError("Couldn't solve for initial conditions")
ValueError: Couldn't solve for initial conditions
由于某些原因,SymPy很难解这个方程,这个方程很容易手工求解。
解决方案
正如OSCAR指出的那样,dsolve无法求解ODE,因为只需要一个初始条件。然而,为了1)求解常微分方程和2)确定参数k,这两个条件都是必需的。这两个条件必须分开完成。下面的代码实现了这一点:
from sympy import Function, Derivative, dsolve, solve, symbols, Eq
t, k = symbols('t,k', real=True)
t1 = 0
M1 = 100
t2 = 6
M2 = 97
M = Function('M')(t)
M_ = Derivative(M,t)
Eqn = Eq(M_,k*M)
sol = dsolve(Eqn, ics={M.subs(t,t1): M1})
expr = sol.rhs.subs(t,t2)
eqn2 = Eq(expr,M2)
k_value = float(solve(eqn2,k)[-1])
sol_with_k = sol.subs(k,k_value)
print(sol_with_k)
下列哪项给出了正确的输出:
Eq(M(t), 100*exp(-0.00507653458078476*t))
相关文章