Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all coefficients in sympy

Tags:

python

sympy

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

Here I want to extract all the coefficients of x, x**2 (and so on), like;

# 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;

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}
like image 978
akai Avatar asked Apr 09 '14 07:04

akai


People also ask

How do you extract a coefficient in an equation in Python?

coeff(x, n) method. With the help of sympy. coeff(x, n) method, we are able to find the coefficient of variables in mathematical expressions.

How do you display formula in SymPy?

Although you first declare x as a sympy. Symbol , once you perform the assignment x=y+z , x becomes an alias for y+z . Whenever you use x from that point after, x will be automatically translated by python as y+z . If you insist on this workflow, you could use Eq(S('x'),y+z) to display the equation.


3 Answers

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] 
like image 194
Kundan Avatar answered Sep 28 '22 04:09

Kundan


The easiest way is to use Poly

>>> a = Poly(expr, x) >>> a.coeffs() [1, 2*a + 1, 3] 
like image 24
asmeurer Avatar answered Sep 28 '22 03:09

asmeurer


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()
  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}
like image 35
smichr Avatar answered Sep 28 '22 05:09

smichr