runner65
runner65

Reputation: 3

Extract coefficients of SymPy expression containing Derivative

I have the following expression:

T = 0.5*m*(r(t)**2*Derivative(theta(t), t)**2 + Derivative(r(t), t)**2)

I would like to extract the coefficients of Derivative(theta(t), t) and Derivative(r(t), t) to get: 0.5*m*r(t)**2 and 0.5*m, respectively.

I tried:

cr = T.coeff(Derivative(r(t), t),2)
ctheta = T.coeff(Derivative(theta(t), t),2)

but I get the following error:

'r' object is not callable

Is there a way to accomplish this? Thanks!

Upvotes: 0

Views: 184

Answers (1)

Davide_sd
Davide_sd

Reputation: 13185

Check which version of sympy you are using with import sympy;print(sympy.__version__). You might want to update to version 1.11.1.

from sympy import *
t, m = symbols("t, m")
r, theta = [Function(e) for e in ["r", "theta"]]
T = m / 2 * (r(t)**2 * Derivative(theta(t), t)**2 + Derivative(r(t), t)**2)

Let's expand the expression and then call the coeff method:

T.expand().coeff(Derivative(r(t), t), 2)
# out: m/2
T.expand().coeff(Derivative(theta(t), t), 2)
# out: m*r(t)**2/2

Upvotes: 0

Related Questions