简体   繁体   English

为什么 sympy 不能正确求解多项式?

[英]Why doesn't sympy solve polynomials correctly?

Maybe sympy shouldn't be used this way but the following is pretty self explanatory.也许sympy不应该这样使用,但以下内容是不言自明的。 My first equation isn't solved correctly because a degree 3 real polynomial must have real solution(s).我的第一个方程没有正确求解,因为 3 次实数多项式必须有实数解。 And the result for the second polynomial is weird in the sense that sympy should know when the imaginary part is zero.第二个多项式的结果很奇怪,因为sympy应该知道虚部何时为零。 Or what is the best way for returning only real solutions?或者只返回真实解决方案的最佳方法是什么?

Python 3.5.0 (default, Sep 27 2015, 12:06:50) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import *
>>> rho = symbols('rho')
>>> targetPoly = -0.0834311595130454*rho**3 - 0.0332128137292625*rho**2 + 0.00820751285938945*rho + 0.0014919833998052
>>> solve(targetPoly)
[]
>>> targetPoly = -0.083*rho**3 - 0.033*rho**2 + 0.008*rho + 0.001
>>> solve(targetPoly)
[-0.535556965628361 - 0.e-23*I, -0.0961083762029916 + 0.e-23*I, 0.234074980385569 - 0.e-23*I]
>>> exit()

Removing the last decimal from each coefficient gives you a solution.从每个系数中删除最后一个小数为您提供解决方案。 To get rid of very small values use .evalf(chop=True) :要摆脱非常小的值,请使用.evalf(chop=True)

targetPoly = (-0.083431159513045*rho**3 - 0.033212813729262*rho**2 + 
              0.0082075128593894*rho + 0.001491983399805)
sol = solve(targetPoly)
[expr.evalf(chop=True) for expr in sol]

Result:结果:

[-0.521021972648720, -0.133726616334545, 0.256662143545947]

simplify() also works: simplify()也有效:

[expr.simplify() for expr in sol]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM