我知道这个问题被问过很多次,但是,我仍然无法解决以下问题。我为mean和stdev定义了自己的函数,但是stdev花太长时间才能计算std(Wapproxlist)。因此,我需要解决该问题的方法。
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'
答案 0 :(得分:3)
numpy
不知道如何处理sympy
的{{1}}类型。
Float
在调用(Pdb) type(Wapproxlist[0])
<class 'sympy.core.numbers.Float'>
和np.mean
之前将其转换为numpy数组。
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)))
注意:如果希望加快速度,请避免使用mean=4.177 stdv=10.283
mean=4.180 stdv=10.300
。符号求解器非常酷,但是与浮点计算相比,它们也很慢。