pythonsympycommutativity

The derivative of the product of non-commutative functions


If I use functions in SymPy and call the diff method, the commutative property just gets ignored.

h = Function('h',real=True,commutative=False)(t)
R = Function('R',real=True,commutative=False)(t)
print(diff(R*h,t))
# returns:
R(t)*Derivative(h(t), t) + h(t)*Derivative(R(t), t)

Am I doing something wrong here? I just want the output to have R in the front always..


Solution

  • This is arguably a bug in SymPy, which determines the commutativity of a function from its arguments. See also this comment. It's not related to derivatives: simply printing h*R will expose the bug (the expression is presented as R(t)*h(t)).

    Until this behavior is changed, it seems the only way to achieve the desired result is to declare t to be noncommutative:

    t = Symbol('t', commutative=False)
    h = Function('h', real=True)(t)
    R = Function('R', real=True)(t)
    print(diff(R*h, t))
    

    prints

    R(t)*Derivative(h(t), t) + Derivative(R(t), t)*h(t)