ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 31 Dec 2015 09:20:17 +0100Expanding cos(a*(x+y))https://ask.sagemath.org/question/31927/expanding-cosaxy/ I'm having trouble finding out how to expand
> a*(x+y)
when wrapped by cos().
The expression
> expand(a*(x+y))
expands as expected, but
> expand(cos(a*(x+y)))
, leaves the expression unchanged.
I would prefer a solution that scales for more complex expressionsThu, 31 Dec 2015 01:58:16 +0100https://ask.sagemath.org/question/31927/expanding-cosaxy/Answer by slelievre for <p>I'm having trouble finding out how to expand </p>
<blockquote>
<p>a*(x+y)</p>
</blockquote>
<p>when wrapped by cos().
The expression</p>
<blockquote>
<p>expand(a*(x+y))</p>
</blockquote>
<p>expands as expected, but </p>
<blockquote>
<p>expand(cos(a*(x+y)))</p>
</blockquote>
<p>, leaves the expression unchanged.
I would prefer a solution that scales for more complex expressions</p>
https://ask.sagemath.org/question/31927/expanding-cosaxy/?answer=31933#post-id-31933Here is an exploration of your question. First define a few expressions.
sage: a, x, y = SR.var('a x y')
sage: expr1 = a * (x + y)
sage: expr1
a*(x + y)
sage: expr2 = cos(expr1)
sage: expr2
cos(a*(x + y))
Trying to expand naively.
sage: expand(expr1)
a*x + a*y
sage: expand(expr2)
cos(a*(x + y))
In the case of `expr2` the following does what you want:
sage: expr2.full_simplify()
cos(a*x + a*y)
Not sure how it would scale for more complex expressions though.
Let's see how to explore the expression tree.
From an expression, you can get the operator and the operands as follows.
sage: op = expr2.operator()
sage: op
cos
sage: ops = expr2.operands()
sage: ops
[a*(x + y)]
Then you can form back the expression as follows.
sage: op(*ops)
cos(a*(x + y))
So you could expand the operands and then apply the operator to the expanded operands as follows:
sage: op(*[expr.expand() for expr in ops])
cos(a*x + a*y)
From there, one could imagine writing a recursive function to explore and expand the expression tree.
Thu, 31 Dec 2015 09:20:17 +0100https://ask.sagemath.org/question/31927/expanding-cosaxy/?answer=31933#post-id-31933