Search code examples
pythonnumpympmath

np.roots() causing 'float() argument must be a string or a number' with mp.mpc type problems


I was getting this error:

> float() argument must be a string or a number

So, why does this happen?(I tried commands like np.asarray() but it keeps failing).

mp.mpc(cmath.rect(a,b)))


Solution

  • The items in raizes are actually mpmath.mpc instances rather than native Python complex floats. numpy doesn't know how to deal with mpmath types, hence the TypeError.

    You didn't mention mpmath at all in your original question. The problem would still have been easy to diagnose if you had posted the full traceback, rather than cutting off the most important part at the end:

    In [10]: np.roots(Q)
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-10-f3a270c7e8c0> in <module>()
    ----> 1 np.roots(Q)
    
    /home/alistair/.venvs/mpmath/lib/python3.6/site-packages/numpy/lib/polynomial.py in roots(p)
        220     # casting: if incoming array isn't floating point, make it floating point.
        221     if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
    --> 222         p = p.astype(float)
        223
        224     N = len(p)
    
    TypeError: float() argument must be a string or a number, not 'mpc'
    

    Whenever you ask for help with debugging on this site, please always post the whole traceback rather than just (part of) the last line - it contains a lot of information that can be helpful for diagnosing the problem.


    The solution is simple enough - just don't convert the native Python complex floats returned by cmath.rect to mpmath.mpc complex floats:

    raizes = []
    for i in range(2*n):
       a, f = cmath.polar(l[i])
       if((f>np.pi/2) or (f<-np.pi/2)):
            raizes.append(cmath.rect(a*r,f))
    
    Q = np.poly(raizes)
    
    print(np.roots(Q))
    
    # [-0.35372430 +1.08865146e+00j -0.92606224 +6.72823602e-01j
    #  -0.35372430 -1.08865146e+00j -1.14467588 -9.11902316e-16j
    #  -0.92606224 -6.72823602e-01j]