Python 使用Sympy不'查找系数;t包括平方根(sqrt)作为值

Python 使用Sympy不'查找系数;t包括平方根(sqrt)作为值,python,sympy,symbolic-math,sqrt,Python,Sympy,Symbolic Math,Sqrt,在Symphy中,有一个有用的功能是为给定表达式创建系数字典 然而,我遇到了一个恼人的错误(/特性?),平方根被认为是变量的一部分,而不是系数值的一部分 最起码的例子: from sympy import sqrt, symbols k, t = symbols('k, t') d = 1.5*t + 2.5*sqrt(2)*k d.as_coefficients_dict() 这将返回: {The documentation explicitly states:

在Symphy中,有一个有用的功能是为给定表达式创建系数字典

然而,我遇到了一个恼人的错误(/特性?),平方根被认为是变量的一部分,而不是系数值的一部分

最起码的例子:

from sympy import sqrt, symbols
k, t = symbols('k, t') 
d = 1.5*t + 2.5*sqrt(2)*k 
d.as_coefficients_dict()           
这将返回:

{The documentation explicitly states:

Return a dictionary mapping terms to their Rational coefficient.

So to start with, this is the expected behavior. To see this, you can note that the sqrt is not the problem, rather it is the fact that the coefficient is irrational. If we take a rational coefficient, we get your expected behavior:

>>> from sympy import sqrt, symbols
>>> k, t = symbols('k, t') 
>>> d = 1.5*t + 2.5*sqrt(4)*k 
>>> d.as_coefficients_dict()
{k: 5.00000000000000, t: 1.50000000000000}
{文件明确指出:

返回将术语映射到其有理系数的字典

首先,这是预期行为。要看到这一点,你可以注意到sqrt不是问题所在,而是系数是非理性的。如果我们取一个理性系数,我们得到你的预期行为:

>>> from sympy import sqrt, symbols
>>> k, t = symbols('k, t') 
>>> d = 1.5*t + 2.5*sqrt(2)*k 
>>> {sym : d.coeff(sym) for sym in (k, t)}  
{k: 2.5*sqrt(2), t: 1.50000000000000}
解决问题的一种方法是使用给定变量明确查询每个系数:


来自Symphy import sqrt
我想我已经在使用它了。不过,感谢您注意到了这一点-我已经修改了这个问题。感谢您澄清了预期的行为。您发布的解决方案很好地工作了,谢谢,尽管我现在需要明确指定变量的唯一限制。不过这不是一个大问题。