Python 如何提取sympy中的所有系数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22955888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract all coefficients in sympy
提问by akai
You can get a coefficient of a specific term by using coeff();
您可以使用 coeff() 获得特定项的系数;
x, a = symbols("x, a")
expr = 3 + x + x**2 + a*x*2
expr.coeff(x)
# 2*a + 1
Here I want to extract all the coefficients of x, x**2 (and so on), like;
在这里,我想提取 x、x**2(等等)的所有系数,例如;
# for example
expr.coefficients(x)
# want {1: 3, x: (2*a + 1), x**2: 1}
There is a method as_coefficients_dict(), but it seems this doesn't work in the way I want;
有一种方法 as_coefficients_dict(),但似乎这并不像我想要的那样工作;
expr.as_coefficients_dict()
# {1: 3, x: 1, x**2: 1, a*x: 2}
expr.collect(x).as_coefficients_dict()
# {1: 3, x**2: 1, x*(2*a + 1): 1}
采纳答案by asmeurer
The easiest way is to use Poly
最简单的方法是使用 Poly
>>> a = Poly(expr, x)
>>> a.coeffs()
[1, 2*a + 1, 3]
回答by RDizzl3
One thing you can do is use a dictionary comprehension like so:
您可以做的一件事是使用字典理解,如下所示:
dict = {x**p: expr.collect(x).coeff(x**p) for p in range(1,n)}
where n is the highest power+1. In this case n=3. So you would have the list [1,2]
其中 n 是最高幂 +1。在这种情况下,n=3。所以你会有名单[1,2]
This would give
这会给
dict = {x: (2*a+1), x**2: 1}
Then you can add in the single term with
然后你可以在单项中添加
dict[1] = 3
So
所以
dict = {1:3,x:(2*a+1),x**2:1}
You may also try:
您也可以尝试:
a = list(reversed(expr.collect(x).as_ordered_terms()))
dict = {x**p: a[p],coeff(x**p) for p in range(1,n)}
dict[1] = a[0] # Would only apply if there is single term such as the 3 in the example
where n is the highest power + 1.
其中 n 是最高幂 + 1。
回答by Kundan
all_coeffs()can be sometime better than using coeffs()for a Poly.
The difference lies in output of these both. coeffs()returns a list containing all coefficients which has a value and ignores those whose coefficient is 0whereas all_coeffs()returns all coefficients including those whose coefficient is zero.
all_coeffs()有时可能比使用coeffs()for a更好Poly。不同之处在于这两者的输出。coeffs()返回一个列表,其中包含所有具有值的系数,并忽略系数为 的系数,0而all_coeffs()返回所有系数,包括系数为零的系数。
>>> a = Poly(x**3 + a*x**2 - b, x)
>>> a.coeffs()
[1, a, -b]
>>> a.all_coeffs()
[1, a, 0, -b]
回答by smichr
Collection of coefficients can be handled with Poly and then separation of the monomials into dependent and independent parts can be handled with Expr.as_independent:
可以使用 Poly 处理系数的集合,然后可以使用以下方法将单项式分离为相关部分和独立部分Expr.as_independent:
>>> def codict(expr, *x):
... collected = Poly(expr, *x).as_expr()
... return dict(i.as_independent(*x)[::-1] for i in Add.make_args(collected))
...
>>> codict(y, x)
{1: 3, x**2: 1, x: 2*a + 1}
>>> codict(y+b*z,x,z)
{1: 3, x**2: 1, z: b, x: 2*a + 1}

