问题
SinceSympy
version 1.2, python Sympy
has implemented the ability to solve for the constants in a simple differential equation, given some initial conditions. I was trying to test out this feature, but keep getting an error that I don't know how to solve.
The documentation indicates the following format for initial conditions, and I tried to follow what was specified in the actual pull request that implemented the feature. Here is the code and the error.
import sympy as sp
t = sp.symbols('t')
x = sp.Function('x')(t)
diffeq = sp.Eq(x.diff(t,t) - x, sp.cos(t))
res = sp.dsolve(diffeq, t, ics={x(0): 0,
x.diff(t).subs(t, 0): 0})
The error is:
Traceback (most recent call last):
File "<ipython-input-20-75c3e1d53138>", line 1, in <module>
res = sp.dsolve(diffeq, t, ics={x(0): 0, sp.diff(x(t), t).subs(t,0): 0})
TypeError: 'x' object is not callable
回答1:
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".
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})
(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)
This gives me res =
Eq(x(t), exp(t)/4 - cos(t)/2 + exp(-t)/4)
来源:https://stackoverflow.com/questions/58034695/sympy-solving-differential-equation-with-initial-conditions-error