Mark
Mark

Reputation: 5

Sympy Collect() in trig expression

I’m new to sympy and I’m having trouble using collect() inside a trigonometric function. I am not using simplify() or trigsimp() because my actual expression is more complicated and they oversimplify it. I am trying to simplify it step by step into a particular form. Why doesn’t collect(sin(xy+xz),x) group the x terms? Thanks.

x, y, z = symbols('x y z')

print(collect(sin(2*x + 3*x),x))
sin(5*x)  #Works

print(collect(x*y + x*z, x))
x*(y + z)  #Works

print(collect(sin(x*y+x*z),x))
sin(x*y + x*z)  #Doesn’t work - Expected sin(x(y+z))

Upvotes: 0

Views: 384

Answers (2)

smichr
smichr

Reputation: 19125

If you want to apply a function to arguments of an expression and the function doesn't have a deep option, you can try create a lambda that will apply the function to an arbitrary expression and use that with bottom_up:

>>> from sympy.abc import *
>>> from sympy import *
>>> bottom_up(sin(x+x*y), lambda e: collect(e, x))
sin(x*(y + 1))

A targeted replacement would also work:

>>> sin(x+x*y).replace(lambda e: e.is_Add and e.has(x), lambda e: collect(e,x))
sin(x*(y + 1))

Upvotes: 0

Zichzheng
Zichzheng

Reputation: 1290

For Collect:

user is expected to provide an expression is an appropriate form. This makes :collect more predictable as there is no magic happening behind the scenes.

So, I guess collect have some trouble reading the expression you are giving. Since you says you want step to step answer, I think you can use temp variables to pass the inner expression.

t = collect(x*y + x*z, x)
print(collect(sin(t),x))

This will give you sin(x*(y + z))

Upvotes: 0

Related Questions