只在numpy打印真正的根

rod*_*ocf 15 python numpy python-3.x

我有这样的事情:

coefs = [28, -36, 50, -22]
print(numpy.roots(coefs))
Run Code Online (Sandbox Code Playgroud)

当然结果是:

[ 0.35770550+1.11792657j  0.35770550-1.11792657j  0.57030329+0.j ]
Run Code Online (Sandbox Code Playgroud)

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

0.57030329
Run Code Online (Sandbox Code Playgroud)

gg3*_*349 23

不要使用.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]
Run Code Online (Sandbox Code Playgroud)

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

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

  • +1 - 许多人忘记了数值不精确会导致无关紧要的虚数系数,无论它们有多小,数字仍然会被归类为虚数. (2认同)

Mar*_*cin 6

您可以使用iscomplex如下操作:

r = numpy.roots(coefs)

In [15]: r[~numpy.iscomplex(r)]
Out[15]: array([ 0.57030329+0.j])
Run Code Online (Sandbox Code Playgroud)

您也可以使用isreal,如注释中所指出:

In [17]: r[numpy.isreal(r)]
Out[17]: array([ 0.57030329+0.j])
Run Code Online (Sandbox Code Playgroud)