同情解决没有给出正确的结果 [英] sympy solve not giving correct result

查看:33
本文介绍了同情解决没有给出正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考这个desmos图,我尝试通过以下方式解决x截距:

refer to this desmos graph, I try to solve the x-intercepts by:

import sympy as sym
print(sym.solve('1.0*x**3 - 3.0*x**2 - 25.0*x + 25.0'))
# [-4.25542010777727 - 0.e-22*I, 0.928558406041155 + 0.e-20*I, 6.32686170173611 - 0.e-21*I]

预期输出是浮点值列表.另外,我需要用这个方法来求很多关于x的不同多项式的根,其中一些可能没有根,我担心以后可能会产生一些虚数,有没有办法我可以拒绝虚数值吗?

The expected output is a list of float values. beside, I need to use this method to find roots of a lot of different polynomials with respect to x, some of them may not have a root, I am worried that there may be some imaginary numbers generated in the future, is there a way I can reject imaginary values?

如果有人提供一些建议,我会很高兴.

I will be so glad if someone offer some suggestion.

推荐答案

正如你可以从 WolframAlphasympy 找到的根确实是多项式的根.

As you can verify from WolframAlpha, the roots found by sympy are indeed the roots of your polynomial.

可能是由于 sympy 实现的算法,有一些浮点/舍入错误导致虚构的遗留"学期.但是,如您所见,它几乎等于零(~ e-22).

Likely due to the algorithm implemented by sympy, there are some floating point / rounding errors resulting in an imaginary "left-over" term. However, as you can see, it is almost equal to zero (~ e-22).

为了保留解决方案的真实部分,您可以执行以下操作

To just keep the real part of the solution, you could do the following

import sympy as sym
res = sym.solve('1.0*x**3 - 3.0*x**2 - 25.0*x + 25.0')
res = [x.as_two_terms()[0] for x in res]
print(res)

这篇关于同情解决没有给出正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆