簡體   English   中英

如何提取sympy中的所有系數

[英]How to extract all coefficients in sympy

您可以使用 coeff() 獲得特定項的系數;

x, a = symbols("x, a")
expr = 3 + x + x**2 + a*x*2
expr.coeff(x)
# 2*a + 1

這里我想提取 x, x**2 (等等)的所有系數,比如;

# for example
expr.coefficients(x)
# want {1: 3, x: (2*a + 1), x**2: 1}

有一種方法 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}

all_coeffs()有時比對Poly使用coeffs()更好。 不同之處在於這兩者的輸出。 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]

最簡單的方法是使用Poly

>>> a = Poly(expr, x)
>>> a.coeffs()
[1, 2*a + 1, 3]

您可以做的一件事是使用字典理解,如下所示:

dict = {x**p: expr.collect(x).coeff(x**p) for p in range(1,n)}

其中 n 是最高冪 +1。 在這種情況下,n=3。 所以你會有列表[1,2]

這會給

dict = {x: (2*a+1), x**2: 1}

然后你可以在單項中添加

dict[1] = 3

所以

 dict = {1:3,x:(2*a+1),x**2:1}

您也可以嘗試:

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

其中 n 是最高冪 + 1。

可以使用 Poly 處理系數的集合,然后可以使用Expr.as_independent處理將單項式分離為相關部分和獨立部分:

def codict(expr, *x):
  collected = Poly(expr, *x).as_expr()
  i, d = collected.as_independent(*x, as_Add=True)
  rv = dict(i.as_independent(*x, as_Mul=True)[::-1] for i in Add.make_args(d))
  if i:
      assert 1 not in rv
      rv.update({S.One: i})
  return rv

>>> var('a x z y')
(a, x, z, y)
>>> expr = 3 + x + x**2 + a*x*2
>>> codict(expr, x)
{x**2: 1, x: 2*a + 1, 1: 3}
>>> codict(expr+y+z, x)
{x**2: 1, x: 2*a + 1, 1: y + z + 3}
>>> codict(expr+y+z, x,y)
{y: 1, x**2: 1, x: 2*a + 1, 1: z + 3}
>>> codict(expr+y+z, x,y,z)
{y: 1, z: 1, x**2: 1, x: 2*a + 1, 1: 3}

根據RDizzl3的回答,我修改如下:

d_c = collect(my_poly, x)
# replace n by highest power + 1 
dict = {x**p: d_c.coeff(x, p) for p in range(0,n)}

這不會跳過常量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM