只在numpy打印真正的根

时间:2015-01-22 04:21:35

标签: python python-3.x numpy

我有这样的事情:

coefs = [28, -36, 50, -22]
print(numpy.roots(coefs))

当然结果是:

[ 0.35770550+1.11792657j  0.35770550-1.11792657j  0.57030329+0.j ]

然而,通过使用这种方法,如何才能获得它(如果有的话)(如浮点数)?我的例子就是这个意思:

0.57030329

3 个答案:

答案 0 :(得分:24)

请勿使用.iscomplex().isreal(),因为roots()是一种数值算法,它返回多项式实际根的数值近似值。这可能导致虚假的虚部,由上述方法解释为解决方案。

示例:

# create a polynomial with these real-valued roots:
p = numpy.poly([2,3,4,5,56,6,5,4,2,3,8,0,10])
# calculate the roots from the polynomial:
r = numpy.roots(p)
print(r) # real-valued roots, with spurious imaginary part
array([ 56.00000000 +0.00000000e+00j,  10.00000000 +0.00000000e+00j,
         8.00000000 +0.00000000e+00j,   6.00000000 +0.00000000e+00j,
         5.00009796 +0.00000000e+00j,   4.99990203 +0.00000000e+00j,
         4.00008066 +0.00000000e+00j,   3.99991935 +0.00000000e+00j,
         3.00000598 +0.00000000e+00j,   2.99999403 +0.00000000e+00j,
         2.00000000 +3.77612207e-06j,   2.00000000 -3.77612207e-06j,
         0.00000000 +0.00000000e+00j])
# using isreal() fails: many correct solutions are discarded
print(r[numpy.isreal(r)])
[ 56.00000000+0.j  10.00000000+0.j   8.00000000+0.j   6.00000000+0.j
   5.00009796+0.j   4.99990203+0.j   4.00008066+0.j   3.99991935+0.j
   3.00000598+0.j   2.99999403+0.j   0.00000000+0.j]

根据您手头的问题使用一些阈值。此外,既然你对真正的根源感兴趣,那么只保留真正的部分:

real_valued = r.real[abs(r.imag)<1e-5] # where I chose 1-e5 as a threshold
print(real_valued)

答案 1 :(得分:5)

您可以使用iscomplex执行此操作,如下所示:

r = numpy.roots(coefs)

In [15]: r[~numpy.iscomplex(r)]
Out[15]: array([ 0.57030329+0.j])

此外,您可以使用评论中指出的isreal

In [17]: r[numpy.isreal(r)]
Out[17]: array([ 0.57030329+0.j])

答案 2 :(得分:0)

我希望这有帮助。

 roots = np.roots(coeff);
 for i in range(len(roots)):
     if np.isreal(roots[i]):
         print(np.real(roots[i]))
相关问题