gpt4 book ai didi

python - 仅在 numpy 中打印真正的根

转载 作者:太空狗 更新时间:2023-10-29 17:12:38 25 4
gpt4 key购买 nike

我有这样的东西:

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

当然结果是:

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

但是,通过使用这种方法,我如何让它只打印真正的根(如果有的话)(作为 float )?对于我的例子来说就是这个意思:

0.57030329

最佳答案

不要使用.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)

关于python - 仅在 numpy 中打印真正的根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28081247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com