Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Standard Deviation AttributeError: 'Float' object has no attribute 'sqrt'

I know this was asked many times, but, I am still having trouble with the following problem. I defined my own functions for mean and stdev, but stdev takes too long to calculate std(Wapproxlist). So, I need a solution for the issue.

import numpy as np
def Taylor_Integration(a, b, mu):
    import sympy as sy
    A, B, rho = sy.symbols('A B rho', real=True)
    Wapp = (A + B*rho - rho/(2*mu*(1 - rho)))**2
    eq1 = sy.diff(sy.integrate(Wapp, (rho, a, b)),A)
    eq2 = sy.diff(sy.integrate(Wapp, (rho, a, b)),B)
    sol = sy.solve([eq1,eq2], [A,B])
    return sol[A], sol[B]

def Wapprox(rho, A, B):
    return A + B*rho

def W(mu, rho):
    return rho/(2*mu*(1-rho))

Wapproxlist = []
Wlist = []
alist = np.linspace(0, 0.98, 10)

for a in alist:
    b = a+0.01; mu = 1
    A, B = Taylor_Integration(a, b, mu)
    rholist = np.linspace(a, b, 100)
    for rho in rholist:
        Wapproxlist.append(Wapprox(rho, A, B))
        Wlist.append(W(mu, rho))

print('mean=%.3f stdv=%.3f' % (np.mean(Wapproxlist), np.std(Wapproxlist)))
print('mean=%.3f stdv=%.3f' % (np.mean(Wlist), np.std(Wlist)))

Output:

AttributeError                            Traceback (most recent call last)
<ipython-input-83-468c8e1a9f89> in <module>()
----> 1 print('mean=%.3f stdv=%.3f' % (np.mean(Wapproxlist), np.std(Wapproxlist)))
      2 print('mean=%.3f stdv=%.3f' % (np.mean(Wlist), np.std(Wlist)))

C:\Users\2tc\.julia\v0.6\Conda\deps\usr\lib\site-packages\numpy\core\fromnumeric.pyc in std(a, axis, dtype, out, ddof, keepdims)
   3073 
   3074     return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
-> 3075                          **kwargs)
   3076 
   3077 

C:\Users\2tc\.julia\v0.6\Conda\deps\usr\lib\site-packages\numpy\core\_methods.pyc in _std(a, axis, dtype, out, ddof, keepdims)
    140         ret = ret.dtype.type(um.sqrt(ret))
    141     else:
--> 142         ret = um.sqrt(ret)
    143 
    144     return ret

AttributeError: 'Float' object has no attribute 'sqrt'
like image 397
tcokyasar Avatar asked Jul 31 '18 15:07

tcokyasar


1 Answers

numpy doesn't know how to handle sympy's Float type.

(Pdb) type(Wapproxlist[0])
<class 'sympy.core.numbers.Float'>

Convert it to a numpy array before calling np.mean and np.std.

Wapproxlist = np.array(Wapproxlist, dtype=np.float64) # can use np.float32 as well

print('mean=%.3f stdv=%.3f' % (np.mean(Wapproxlist), np.std(Wapproxlist)))
print('mean=%.3f stdv=%.3f' % (np.mean(Wlist), np.std(Wlist)))

output:

mean=4.177 stdv=10.283
mean=4.180 stdv=10.300

Note: If you're looking to speed this up, you'll want to avoid sympy. Symbolic solvers are pretty cool, but they're also very slow compared to floating point computations.

like image 189
Matt Messersmith Avatar answered Nov 19 '22 12:11

Matt Messersmith