Sympy未能解决线性ODE系统

时间:2014-12-04 10:29:47

标签: python sympy

我最近开始使用sympy用python进行符号计算。现在,我正在与ODE合作,昨天我试图解决非常简单的初始值问题:

    y1'   =    y1 + 2 y2,
    y2'   = -2 y1 +   y2 + 2 exp(t),

初始条件

    y1(0) =  y2(0) = 1

我编写的python代码如下:

>>> import sympy as sy    
>>> t=sy.symbols('t')
>>> y1=sy.Function('y1')   
>>> y2=sy.Function('y2')
>>> eqs=(sy.Eq(y1(t).diff(t),y1(t)+2*y2(t)), sy.Eq(y2(t).diff(t),-2*y1(t)+y2(t)+2*sy.exp(t))) 
>>> s=sy.dsolve(eqs)        # General solution
>>> s
[y1(t) == 2*(C1*sin(2*t) + C2*cos(2*t))*exp(t),
 y2(t) == (2*C1*cos(2*t) - 2*C2*sin(2*t))*exp(t)]
>>> y1g=s[0].args[1]
>>> y2g=s[1].args[1]
>>> # Find C1 and C2 so that the initial condition is satisfied
>>> sol=sy.solve([y1g.subs(t,0)-1,y2g.subs(t,0)-1])
>>> sol
{C1: 1/2, C2: 1/2}
>>> y1=y1g.subs(sol)
>>> y2=y2g.subs(sol)
>>> [y1,y2]
[2*(sin(2*t)/2 + cos(2*t)/2)*exp(t), (-sin(2*t) + cos(2*t))*exp(t)]

但解决方案是错误的!我犯了错误还是这是一个问题错误?

1 个答案:

答案 0 :(得分:0)

免责声明:这不是一个答案,而是一个需要严格格式化的评论

我将代码的第一部分复制到文件中

% cat sy.py
import sympy as sy    
t=sy.symbols('t')
y1=sy.Function('y1')   
y2=sy.Function('y2')
eqs=(sy.Eq(y1(t).diff(t),y1(t)+2*y2(t)), sy.Eq(y2(t).diff(t),-2*y1(t)+y2(t)+2*sy.exp(t))) 
s=sy.dsolve(eqs)
%

后来我在上面运行python

% python2.7 sy.py 
Traceback (most recent call last):
  File "sy.py", line 6, in <module>
    s=sy.dsolve(eqs)
  File "/usr/lib/python2.7/dist-packages/sympy/solvers/ode.py", line 525, in dsolve
    x0=x0, n=n, **kwargs)
  File "/usr/lib/python2.7/dist-packages/sympy/solvers/deutils.py", line 174, in _desolve
    eq, func = _preprocess(eq, func)
  File "/usr/lib/python2.7/dist-packages/sympy/solvers/deutils.py", line 72, in _preprocess
    derivs = expr.atoms(Derivative)
AttributeError: 'tuple' object has no attribute 'atoms'
% 

你所说的和我得到的东西之间存在差异。也许这是我的错。