[SOLVED] Finding coefficients using Sympy doesn't include square root (sqrt) as value

By SLhark

In SymPy, there is a useful feature to create a dictionary of coefficients for a given expression.

However, I'm encountering an irritating bug (/feature?) whereby square roots are considered to be part of the variable, and not part of the coefficient value.

Minimum example:

``````from sympy import sqrt, symbols
k, t = symbols('k, t')
d = 1.5*t + 2.5*sqrt(2)*k
d.as_coefficients_dict()
``````

This returns:

``````{𝑡:1.5, sqrt(2)*𝑘:2.5}
``````

When instead, the sqrt(2) should be considered as part of the coefficient. Thus, I expected to see the result:

``````{𝑡:1.5, 𝑘:2.5*sqrt(2)}
``````

NB, I'm using the latest SymPy version 1.4

Is this a bug? Or an alternative way to use the function to get the expected value please?

EDIT: I amended the question to note that I am using the Sympy sqrt function. I also tried using NumPy's np.sqrt, which evaluates correctly, but gives the full numerical value rather than a nice neat sqrt(2) for the value of the k coefficient. 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}
``````

One way to solve your problem is to explicitly inquire about each coefficient with the given variables:

``````>>> 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}
`````` @SLhark 2019-04-15 11:37:07

Thanks for clarifying the expected behaviour. The workaround you posted works nicely thanks, although with the only limitation that I now need to explicitly specify the variables. This isn't a big issue though.

Rounding coefficients of a symbolic expression in SymPy

• 2018-01-31 23:33:56
• Bartosz Muszyński
• 235 View
• 1 Score
• Tags:   python sympy

[SOLVED] Sympy matrix substitution using a dictionary

• 2015-04-15 15:33:53
• Moritz
• 318 View
• 0 Score
• Tags:   python sympy