# Collect is not collecting properly with non-commutative algebra

I'm using the NCAlgebra package to do some error analysis of operator split methods. I am trying to reproduce the simple examples in Mathematica, but I'm coming across some strange behavior and I think it may all be related to me doing something wrong.

If I look at finding the error for Lie operator splitting and Strang operator splitting, the results come out strange:

<< NC
<< NCAlgebra

SetCommutative[dt, u0];
SetNonCommutative[Dx];
SetNonCommutative[B];

ue = (1 + dt*(Dx + B) + dt^2/2*(Dx + B)^2 + dt^3/6*(Dx + B)^3)*u0;

uL = ((1 + dt*Dx + dt^2/2*Dx^2 + dt^3/6*Dx^3) ** (1 + dt*B +
dt^2/2*B^2 + dt^3/6*B^3))*u0;

uS = ((1 + (dt/2)*Dx + (dt/2)^2/2*Dx^2 + (dt/2)^3/6*
Dx^3 + (dt/2)^4/Factorial*Dx^4 + (dt/2)^5/Factorial*
Dx^5) ** (1 + dt*B + dt^2/2*B^2 +
dt^3/6*B^3) ** (1 + (dt/2)*Dx + (dt/2)^2/2*Dx^2 + (dt/2)^3/6*
Dx^3 + (dt/2)^4/Factorial*Dx^4 + (dt/2)^5/Factorial*
Dx^5))*u0;

Substitute[
NCCollect[NCExpand[(uL - ue)/u0], {dt, dt^2, dt^3}], {dt^3 -> 0,
dt^4 -> 0, dt^5 -> 0, dt^6 -> 0, dt^7 -> 0, dt^8 -> 0, dt^9 -> 0,
dt^10 -> 0, dt^11 -> 0, dt^12 -> 0}]
Substitute[
NCCollect[NCExpand[(uS - ue)/u0], {dt, dt^2, dt^3}], {dt^4 -> 0,
dt^5 -> 0, dt^6 -> 0, dt^7 -> 0, dt^8 -> 0, dt^9 -> 0, dt^10 -> 0,
dt^11 -> 0, dt^12 -> 0, dt^13 -> 0}]


Okay, so it seems simple enough (although really ugly -- I know, Mathematica is not more forte). The results I get are:

-B dt^2 Dx + dt^2 Dx ** B

dt^2 (-B Dx - Dx^2/4) + dt^3 (-((B^2 Dx)/2) - Dx^3/8 - B ** Dx^2/2) +
dt^2 (B ** Dx/2 + Dx ** B/2 + Dx ** Dx/4) +
dt^3 (B ** Dx^2/8 + B^2 ** Dx/4 + Dx ** B^2/4 + Dx ** Dx^2/16 +
Dx^2 ** B/8 + Dx^2 ** Dx/16 + Dx ** B ** Dx/4)


So now my issues/concerns/questions:

1. Why is it not collecting terms correctly? For example, it didn't collect in dt^2 in the first result and didn't collect everything in either dt^2 or dt^3 in the second.
2. Why would it think that B Dx is different from B ** Dx? Likewise, it thinks Dx^2 is not the same as Dx ** Dx. And how does it even make sense that a variable would not commute with itself?

Something tells me I input something weird/wrong and that's why it's doing this.

Any insight would be helpful. This is the first step and I'd hate to have to return to pen-and-paper doing these multiplications.

• Also, please feel free to add the correct tags. I have no clue what tags would be appropriate... Dec 3, 2016 at 1:03

I am not completely sure about what you want to do but you should call NCCollect (or standard Collect) on dt alone. For example:
NCCollect[NCExpand[(uL - ue)/u0], {dt}]

Because in your case dt is commutative the standard Mathematica Collect will also work. For the same reason you do not need Substitute, but ReplaceAll. Note that in recent versions of NCAlgebra Substitute has been replaced by the more powerful and consistent NCReplaceAll.
Looks like you're doing some kind of directional derivative. If so, check out the command NCDirectionalD.