6
$\begingroup$

I have an expression that I want Mathematica to fully expand without any simplification afterwards. I want the output to look like the following example.

(x+y)^2 ⇒ x^2+xy+yx+y^2

Could you help me to solve this problem?

$\endgroup$
2
  • 3
    $\begingroup$ Something like Distribute[(x + y) ** (x + y)] /. t_ ** t_ :> t^2? $\endgroup$ Commented Oct 6, 2012 at 14:37
  • $\begingroup$ By the way, welcome to Mathematica.SE, Parisa! Please consider registering your account. You will then be able to accumulate your reputation points no matter where you post from, and thus be able to do more on the site over time, such as vote up and participate in chat. $\endgroup$
    – Verbeia
    Commented Oct 6, 2012 at 23:46

2 Answers 2

10
$\begingroup$

Try

Expand[(x + y)^2] 

which will give you

$ x^2 + 2 x y + y^2$

Even ExpandAll[] won't separate the $"2 xy"$ into $"xy+yx"$. And this makes sense; what should it make of $"3xy"$? $"xy + yx + xy"$, or $"xy + yx +yx"$? And what about $"10 xy"$ (I don't want to think about $"10000 xy"$)?

J.M.'s solution

Distribute[(x + y) ** (x + y)] /. t_ ** t_ :> t^2  

will give you the $2 x y$ as separate terms, but has to use the symbol for non-commutative multiplication (for example, x and y may be operators):

$ x^2 + y^2 + x ** y + y** x $

and Mathematica won't interpret it as commutative multiplication. Replacing x and y with numerical values

x^2 + y^2 + x ** y + y ** x /. {x -> 2, y -> 3}

will yield

$13 + 2 ** 3 + 3 ** 2$

instead of

$ 25$

$\endgroup$
3
$\begingroup$
Defer@*Plus @@ (If[SameQ[##], Times, CenterDot][##] & @@@ Tuples[{x, y}, 2])
% /. {x -> 3, y -> 4}

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.