[英]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).
我为mean和stdev定义了自己的函数,但是stdev花太长时间才能计算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)))
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'
numpy
doesn't know how to handle sympy
's Float
type. numpy
不知道如何处理sympy
的Float
类型。
(Pdb) type(Wapproxlist[0])
<class 'sympy.core.numbers.Float'>
Convert it to a numpy array before calling np.mean
and np.std
. 在调用
np.mean
和np.std
之前,将其转换为numpy数组。
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
. 注意:如果您希望加快速度,请避免使用
sympy
。 Symbolic solvers are pretty cool, but they're also very slow compared to floating point computations. 符号求解器很酷,但是与浮点计算相比,它们也很慢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.