How to extract common factors of trigonometric functions using sympy?

Viewed 68

I am new to using sympy. I checked the tutorial on the official website. There is only the "sym.collect" function for extracting common factors, but it does not support the common factors of trigonometric functions. Here is my code:

F0,w = symbols('F0,w')
m1,m2,c,k1,k2,t = symbols('m1,m2,c,k1,k2,t')
c1, c2, d1, d2 = symbols('c1,c2,d1,d2')
res = -F0*sin(t*w) + c*c1*w*cos(t*w) - c*c2*w*sin(t*w) - c*d1*w*cos(t*w) + \
c*d2*w*sin(t*w) + c1*k1*sin(t*w) + c1*k2*sin(t*w) - \
c1*m1*w**2*sin(t*w) + c2*k1*cos(t*w) + c2*k2*cos(t*w) - c2 * \
m1*w**2*cos(t*w) - d1*k2*sin(t*w) - d2*k2*cos(t*w)
sym.collect(res,sin)

turn out:

ValueError: keyfunc gave non-binary output

The result I want to get is:

  sin(wt)*(-F0- c*c2*w +  c*d2*w + ....) + cos(wt)*(c*c1*w + ...) 

So how can I fix it?

2 Answers

The collection can be done by passing one or more expressions, too:

collect(mid, (sin(t*w), cos(t*w)))

I have solved it.

q = symbols('q')
mid = sym.collect(res1.subs(cos(t*w), q), q).subs(q, cos(t*w))
Related