也许sympy
不应该以这种方式使用,但以下内容非常自我解释。我的第一个方程未正确求解,因为3次实数多项式必须具有实数解。并且第二个多项式的结果在sympy
当虚部为零时应该知道的意义上是奇怪的。或者只返回真正解决方案的最佳方式是什么?
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()
答案 0 :(得分:1)
从每个系数中删除最后一个小数为您提供解决方案。要删除非常小的值,请使用.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]
结果:
[-0.521021972648720, -0.133726616334545, 0.256662143545947]
simplify()
也有效:
[expr.simplify() for expr in sol]