Make all symbols commutative in a sympy expression

左心房为你撑大大i 提交于 2019-12-11 02:22:50

问题


Say you have a number of non commutative symbols within a sympy expression, something like

a, c = sympy.symbols('a c', commutative=False)
b = sympy.Symbol('b')
expr = a * c + b * c

What is the preferred way to make all symbols in the expression commutative, so that, for example, sympy.simplify(allcommutative(expr)) = c * (a + b)?

In this answer it is stated that there is no way to change the commutativity of a symbol after creation without replacing a symbol, but maybe there is an easy way to change in blocks all symbols of an expression like this?


回答1:


If you want Eq(expr, c * (a + b)) to evaluate to True, you'll need to replace symbols by other symbols that commute. For example:

replacements = {s: sympy.Dummy(s.name) for s in expr.free_symbols}
sympy.Eq(expr, c * (a + b)).xreplace(replacements).simplify()

This returns True.




回答2:


Two comments:

  1. noncommutatives will factor (though they respect the side that the nc expr appears on)
  2. although you have a robust answer, a simple answer that will often be good enough is to just sympify the string version of the expression

Both are shown below:

>>> import sympy
>>> a, c = sympy.symbols('a c', commutative=False)
>>> b = sympy.Symbol('b')
>>> expr = a * c + b * c
>>> factor(expr)
(b + a)*c
>>> S(str(_))
c*(a + b)


来源:https://stackoverflow.com/questions/48291209/make-all-symbols-commutative-in-a-sympy-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!