在同情中忽略想象的根源

Kre*_*ade 9 python math sympy

我用sympy来解决多项式:

x = Symbol('x')
y = solve(int(row["scaleA"])*x**3 + int(row["scaleB"])*x**2 + int(row["scaleC"])*x + int(row["scaleD"]), x)
Run Code Online (Sandbox Code Playgroud)

y是可能的解决方案列表.但是,我需要忽略虚构的,只使用真正的解决方案.此外,我希望解决方案作为一个值而不是表达式.现在它看起来像:

[-2/3 - 55**(1/3)*(-1/2 - sqrt(3)*I/2)/3, -2/3 - 55**(1/3)*(-1/2 + sqrt(3)*I/2)/3, -55**(1/3)/3 - 2/3]
Run Code Online (Sandbox Code Playgroud)

我需要最后一个表达式的值(-2.22756).是否有同情函数来简化这一点?

asm*_*rer 9

如果您设置x为真实,SymPy将只为您提供真正的解决方案

x = Symbol('x', real=True)
solve(..., x)
Run Code Online (Sandbox Code Playgroud)

  • 我正在尝试使用这种方法解方程,但它仍然返回虚解 (4认同)

小智 5

solve() 对于各种类型的解决方案没有一致的输出,请使用 solveset(Eq,x,domain=S.Reals)

 from sympy import ImageSet, S 
 x = Symbol('x')
 y = solveset(int(row["scaleA"])*x**3 + int(row["scaleB"])*x**2+int(row["scaleC"])*x + int(row["scaleD"]), x, domain=S.Reals)
Run Code Online (Sandbox Code Playgroud)

http://docs.sympy.org/latest/modules/solvers/solveset.html


Kre*_*ade 2

正如 Krastonov 提到的 mpmath 提供了一种更简单的方法:

y = polyroots([int(row["scaleA"]), int(row["scaleB"]), int(row["scaleC"]), int(row["scaleD"])-value])
for root in y:
   if "j" not in str(root):
       value = root
Run Code Online (Sandbox Code Playgroud)