三次方程的 Sympy 解似乎是错误的并且包含虚数单位

问题描述 投票:0回答:1
from sympy import *
from sympy.abc import x

f = x**3 - 3*x + 1
print(solve(f))

但是,它给出了虚数单位的错误答案。通过

subs
检查也不会返回 0。

python sympy
1个回答
0
投票

让我们尝试将 sympy 计算出的符号解转换为浮点数:

from sympy import *
var("x")
f = x**3 - 3*x + 1
sol = solve(f)
print([s.n() for s in sol])
# [0.347296355333861 - 0.e-23*I, 1.53208888623796 + 0.e-20*I, -1.87938524157182 + 0.e-23*I]

在这里你可以看到非常小的虚部。这些是舍入误差。我们可以用这个删除它们:

print([s.n(chop=True) for s in sol])
# [0.347296355333861, 1.53208888623796, -1.87938524157182]

现在,我将把第一个符号解代入方程:

print(f.subs(x, sol[0]))
# 1 + (-1/2 - sqrt(3)*I/2)*(27/2 + 27*sqrt(3)*I/2)**(1/3) + (-3/((-1/2 - sqrt(3)*I/2)*(27/2 + 27*sqrt(3)*I/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(27/2 + 27*sqrt(3)*I/2)**(1/3)/3)**3 + 9/((-1/2 - sqrt(3)*I/2)*(27/2 + 27*sqrt(3)*I/2)**(1/3))

它看起来并不为零,但我们可以要求 sympy 简化它,如下所示:

print(f.subs(x, sol[0]).simplify())
# 0

如您所见,sympy 计算出的符号解是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.