By default, non-commutative multiplication behaves as

(-W) ** (4 R) //FullForm


while I would like it to simplify as follows, for any object involved that is not a symbol:

(-W) ** (4 R) //FullForm


I could write a set of substitution rules, but I suspect that would be very slow for large number of operations. How should one set this property the most efficient way? Perhaps there is a proper Attribute one can set for NonCommutativeMultiply?


Since in my case only products of two operators appear at a time, I use the following as a workaround

NonCommutativeMultiply[Times[x1_,y1_],Times[x2_,y2_]]:= Times[x1,x2,NonCommutativeMultiply[y1,y2]]

Mathematica seems to order Times as constants first then symbols, which is why this works.

Still wondering how a better more efficient solution would look like.

  • 1
    $\begingroup$ Try Times @@ MapThread[Apply, {{Times, NonCommutativeMultiply}, Transpose[FactorTermsList /@ {-W, 4 R}]}]. Generalization ought to be straightforward. $\endgroup$ – J. M. is away Mar 4 '18 at 17:24
  • $\begingroup$ @J.M. Wow, that line of code looks quite busy... I wonder if that would be the most efficient way for large inputs? $\endgroup$ – Kagaratsch Mar 4 '18 at 17:27
  • $\begingroup$ How large are we talking? $\endgroup$ – J. M. is away Mar 4 '18 at 17:29
  • $\begingroup$ @J.M. Millions of operations. Preferably per second... $\endgroup$ – Kagaratsch Mar 4 '18 at 17:32
  • 2
    $\begingroup$ You might want to add a constraint like Times[x1_?NumericQ, y1_] for safety. $\endgroup$ – J. M. is away Mar 4 '18 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.