np.roots() 导致 'float() argument must be a string or a number' 和 mp.mpc 类型问题
np.roots() causing 'float() argument must be a string or a number' with mp.mpc type problems
我遇到了这个错误:
> float() argument must be a string or a number
那么,为什么会发生这种情况?(我尝试了 np.asarray()
之类的命令,但它总是失败)。
mp.mpc(cmath.rect(a,b)))
raizes
中的项目实际上是 mpmath.mpc
个实例,而不是原生的 Python 复杂浮点数。 numpy 不知道如何处理 mpmath 类型,因此 TypeError
.
您在原始问题中根本没有提到 mpmath。如果您 post 编辑了完整的回溯,而不是在最后切断最重要的部分,那么问题仍然很容易诊断:
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'
每当您在此站点上寻求调试帮助时,请始终 post 整个回溯 而不仅仅是最后一行(的一部分)- 它包含很多有助于诊断问题的信息。
解决方案很简单 - 只是不要将 cmath.rect
返回的原生 Python 复杂浮点数转换为 mpmath.mpc
复杂浮点数:
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]
我遇到了这个错误:
> float() argument must be a string or a number
那么,为什么会发生这种情况?(我尝试了 np.asarray()
之类的命令,但它总是失败)。
mp.mpc(cmath.rect(a,b)))
raizes
中的项目实际上是 mpmath.mpc
个实例,而不是原生的 Python 复杂浮点数。 numpy 不知道如何处理 mpmath 类型,因此 TypeError
.
您在原始问题中根本没有提到 mpmath。如果您 post 编辑了完整的回溯,而不是在最后切断最重要的部分,那么问题仍然很容易诊断:
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'
每当您在此站点上寻求调试帮助时,请始终 post 整个回溯 而不仅仅是最后一行(的一部分)- 它包含很多有助于诊断问题的信息。
解决方案很简单 - 只是不要将 cmath.rect
返回的原生 Python 复杂浮点数转换为 mpmath.mpc
复杂浮点数:
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]