pythonnumpysolver

loop of ufunc does not support argument 0 of type Float which has no callable log method


a = 0.5
b = 1
l = Symbol('l')
l = solve(a*b/2+b/l-1, l)[0]
num = 1-l/b*(r-a*b/2)
-1/l*np.log(num)

gives error TypeError: loop of ufunc does not support argument 0 of type Float which has no callable log method

How should I fix this?


Solution

  • As noted, r is undefined.

    In [83]: a = 0.5
        ...: b = 1
        ...: l = sp.Symbol('l')
        ...: l = sp.solve(a*b/2+b/l-1, l)[0]
        ...: num = 1-l/b*(r-a*b/2)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    Cell In[83], line 5
          3 l = sp.Symbol('l')
          4 l = sp.solve(a*b/2+b/l-1, l)[0]
    ----> 5 num = 1-l/b*(r-a*b/2)
    
    NameError: name 'r' is not defined
    

    But checking l:

    In [84]: l
    Out[84]: 
    1.33333333333333
    
    In [85]: type(l)
    Out[85]: sympy.core.numbers.Float
    

    Trying to take log of that produces your error:

    In [86]: np.log(l)
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    AttributeError: 'Float' object has no attribute 'log'
    
    The above exception was the direct cause of the following exception:
    
    TypeError                                 Traceback (most recent call last)
    Cell In[86], line 1
    ----> 1 np.log(l)
    
    TypeError: loop of ufunc does not support argument 0 of type Float which has no callable log method
    

    sympy has a log that does work:

    In [88]: sp.log(l)
    Out[88]: 
    0.287682072451781
    

    Your l looks like a regular float, but is actually a sympy version. np.log if given a non-numeric array, first makes an array:

    In [89]: np.array(l)
    Out[89]: array(1.33333333333333, dtype=object)
    

    If object dtype it then tries to apply a log METHOD to each element of the array. Almost no one implements a x.log() method.

    In general using numpy with sympy does not work well. Bits and pieces work, but they aren't designed to work together. Use sympy functions when available. sp.lambdify can, in some cases convert an expression to a python function that will work.

    In [92]: import math
    In [93]: math.log(l)
    Out[93]: 0.28768207245178085