我收到了这个错误:
> 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 。如果您发布了完整的回溯,而不是在最后切断最重要的部分,问题仍然很容易诊断:
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'
每当您在此站点上寻求调试帮助时,请始终发布整个回溯,而不仅仅是(部分)最后一行 - 它包含许多有助于诊断问题的信息。
解决方案很简单——只是不要将返回的本机 Python 复杂浮点数转换cmath.rect
为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]