Search code examples
pythonsympysymbolic-mathsqrt

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


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.


Solution

  • 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}