多变量多项式是否存在all_coeffs() ?



我想用sympy提取一个多变量多项式的所有系数(包括零)。

Sympy提供all_coeffs(),但它只适用于单变量。否则我得到这个错误PolynomialError: multivariate polynomials not supported

例如,对于多项式x^3+y^3+x*y+1,我希望输出为[3,3,0,0,0,0,1,0,0,1]

如果你做感兴趣的单项式,那么你可以看到它们的系数是什么在你的表达式。但是,您必须注意在包含x*y*z等项的表达式中请求x*y的单项系数。下面的例程通过将得到的系数中的所有变量归零来处理这个问题。它还有一个创建感兴趣的单项式的例程。

def all_coeffs(expr,*free):
x = IndexedBase('x')
expr = expr.expand()
free = list(free) or list(expr.free_symbols)
pows = [p.as_base_exp() for p in expr.atoms(Pow,Symbol)]
P = {}
for p,e in pows:
if p not in free:
continue
elif p not in P:
P[p]=e
elif e>P[p]:
P[p] = e
reps = dict([(f, x[i]) for i,f in enumerate(free)])
xzero = dict([(v,0) for k,v in reps.items()])
e = expr.xreplace(reps); reps = {v:k for k,v in reps.items()}
return dict([(m.xreplace(reps), e.coeff(m).xreplace(xzero) if m!=1 else e.xreplace(xzero)) for m in monoms(*[P[f] for f in free])])
def monoms(*o):
x = IndexedBase('x')
f = []
for i,o in enumerate(o):
f.append(Poly([1]*(o+1),x[i]).as_expr())
return Mul(*f).expand().args
>>> eq = x**2 + x*y - 3
>>> all_coeffs(eq)
{1: -3, x**2: 1, x**2*y: 0, x*y: 1, y: 0, x: 0}
>>> all_coeffs(eq, x)
{1: -3, x**2: 1, x: y}

最新更新