How to extract all coefficients in sympy

前端 未结 4 617

You can get a coefficient of a specific term by using coeff();

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

相关标签:
4条回答
  • 2020-12-01 05:34

    The easiest way is to use Poly

    >>> a = Poly(expr, x)
    >>> a.coeffs()
    [1, 2*a + 1, 3]
    
    0 讨论(0)
  • 2020-12-01 05:39

    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 0 whereas all_coeffs() returns all coefficients including those whose coefficient is zero.

    >>> a = Poly(x**3 + a*x**2 - b, x)
    >>> a.coeffs()
    [1, a, -b]
    
    >>> a.all_coeffs()
    [1, a, 0, -b]
    
    0 讨论(0)
  • 2020-12-01 05:40

    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:

    >>> 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}
    
    0 讨论(0)
  • 2020-12-01 05:44

    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]

    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.

    0 讨论(0)
提交回复
热议问题