且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Sympy:求解具有初始条件误差的微分方程

更新时间:2022-06-26 23:59:26

我不是sympy的重度用户,但我确实可以使用它-问题是,当您定义 x = sp.Function('x')(t)时,您已经参数 t 传递给它,并且不能再在该行上为其传递 0 res = sp.dsolve(diffeq,t,ics = {x(0):0,sp.diff(x(t),t).subs(t,0):0})-用(t)调用 x 使其成为定义函数".

I am not a heavy user of sympy, but I got that to work - the problem is that when you define x = sp.Function('x')(t) you already got the parameter t to it, and can no longer pass 0 for it at the line res = sp.dsolve(diffeq, t, ics={x(0): 0, sp.diff(x(t), t).subs(t,0): 0}) - The call of x with (t) makes it a "defined function".

因此,将 x 保留为未定义函数,并在创建微分方程时仅在需要的点传递 t 即可:

So, leaving x as an undefined function, and just passing t for it in the points it is needed when creating the differential equation is the way to go:


import sympy as sp

t = sp.symbols('t')
x = sp.Function('x')

diffeq = sp.Eq(x(t).diff(t, t) - x(t), sp.cos(t)) 
res = sp.dsolve(diffeq, ics={x(0): 0, sp.diff(x(t), t).subs(t,0): 0})

(此外,尝试在第二个参数中传递 t 做dsolve会出现另一个错误.

(Also, trying to pass t in the second parameter do dsolve gives another error. The docs tell that sympy should be able to correctly guess it, so I left it out - only to find the correct argument there would be x(t) later)

这给了我res =

Eq(x(t), exp(t)/4 - cos(t)/2 + exp(-t)/4)