简体   繁体   中英

How to solve equations with symbolic coefficients and noncommutative variables in SymPy?

I want to solve quite simple equations with symbolic coefficients:

from sympy import *

a, b = symbols('a b', commutative=False)
x = IndexedBase('x')
basis = [a, b, a * b - b * a]
el = b * a - a * b
coefs = [x[k] for k in range(len(basis))]
eq = el - sum([c * bel for c, bel in zip(coefs, basis)])
solve(eq.expand(), coefs)

You can separate the terms of the original expression by free symbols (limited to a and b ) and then solve them independently:

from sympy import ordered
byfree = sift(eq.args, lambda x: tuple(ordered(x.free_symbols&{a,b})))
solve([Add(*v) for v in byfree.values()], coefs)
{x[2]: -1, x[0]: 0, x[1]: 0}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM