简体   繁体   中英

Why doesn't sympy solve polynomials correctly?

Maybe sympy shouldn't be used this way but the following is pretty self explanatory. My first equation isn't solved correctly because a degree 3 real polynomial must have real solution(s). And the result for the second polynomial is weird in the sense that sympy should know when the imaginary part is zero. 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) :

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:

[expr.simplify() for expr in sol]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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