如何提取sympy中的所有系数 [英] How to extract all coefficients in sympy

查看:87
本文介绍了如何提取sympy中的所有系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用coeff()可以得到特定项的系数;

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

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

# 例如expr.coefficients(x)# 想要 {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}

解决方案

最简单的方法是使用Poly

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

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}

解决方案

The easiest way is to use Poly

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

这篇关于如何提取sympy中的所有系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆