Simplifying trigonometric expression

37 views
Skip to first unread message

Paul Royik

unread,
Feb 18, 2016, 4:44:00 AM2/18/16
to sympy
I'm trying to simplify a*cos(b)**2+a*sin(b)**2 to a

So, I write

a = sympy.Wild('a')
b = sympy.Wild('b')
expr = 49*cos(x)**2+49*sin(x)**2 + 5
expr.replace(a*sympy.sin(b)**2+a*sympy.cos(b)**2, a, exact=True)


But this doesn't work. expr is unchanged.

Oscar Benjamin

unread,
Feb 18, 2016, 4:57:21 AM2/18/16
to sympy
How about:

>>> x = Symbol('x')
>>> trigsimp(49*cos(x)**2 + 49*sin(x)**2 + 5)
54

Or is your question about the fact that expr.replace does not modify
expr but rather returns a different expression? Maybe you wanted
something like:

expr = expr.replace(...)

--
Oscar

Shekhar Prasad Rajak

unread,
Feb 18, 2016, 9:22:51 AM2/18/16
to sympy
You can use this :

a,b,c = symbols('a b c')
expr = 49*cos(x)**2+49*sin(x)**2 + 5
expr.replace(a*sin(b)**2+a*cos(b)**2, a, exact=True)
# output 49*sin(x)**2 + 49*cos(x)**2 + 5

Aaron Meurer

unread,
Feb 18, 2016, 11:47:38 AM2/18/16
to sy...@googlegroups.com
I think replace doesn't match subexpressions in an Add, because it
isn't a subtree in the expression tree. This sort of thing needs to be
improved.

This workaround seems to work

In [23]: c = Wild('c', exclude=[sin(x), cos(x)])

In [24]: expr.replace(a*sympy.sin(b)**2+a*sympy.cos(b)**2 + c, a + c)
Out[24]: 54

However, putting the right thing in the exclude parameter is
important. Otherwise, you get stuff like

In [16]: c = Wild('c')

In [17]: expr.replace(a*sympy.sin(b)**2+a*sympy.cos(b)**2 + c, a + c)
Out[17]:
2 2
- 49⋅sin (x) - 49⋅cos (x) + 103

which is technically correct (49 + 5 = -49 + 103), but probably not
what you want.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/ad070b63-17ad-485f-b1e1-4ccd9c4cbc4f%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages