Given some f and the differential equation x'(t) = f(x(t)), how do I compute x(n)(t) in terms of x(t)?
For example, given f(x(t)) = sin(x(t)), I want to obtain x(3)(t) = (cos(x(t))2 − sin(x(t))2) sin(x(t)).
So far I've tried
>>> from sympy import diff, sin
>>> from sympy.abc import x, t
>>> diff(sin(x(t)), t, 2)
which gives me
-sin(x(t))*Derivative(x(t), t)**2 + cos(x(t))*Derivative(x(t), t, t)
but I'm not sure how to tell SymPy what Derivative(x(t), t)
is and have it figure out Derivative(x(t), t, t)
, etc. automatically.
Answer:
Here's my final solution based on the answers I received below:
def diff(x_derivs_known, t, k, simplify=False):
try: n = len(x_derivs_known)
except TypeError: n = None
if n is None:
result = sympy.diff(x_derivs_known, t, k)
if simplify: result = result.simplify()
elif k < n:
result = x_derivs_known[k]
else:
i = n - 1
result = x_derivs_known[i]
while i < k:
result = result.diff(t)
j = len(x_derivs_known)
x0 = None
while j > 1:
j -= 1
result = result.subs(sympy.Derivative(x_derivs_known[0], t, j), x_derivs_known[j])
i += 1
if simplify: result = result.simplify()
return result
Example:
>>> diff((x(t), sympy.sin(x(t))), t, 3, True)
sin(x(t))*cos(2*x(t))