Deepleeqe
Deepleeqe

Reputation: 317

Why sympy gives complex roots when solving cubic equations

I am using the following code to solve a cubic equation.

from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
print(solve(-0.0643820896731566*x**3 + 0.334816369385245*x**2 + 1.08104426781115*x - 2.05750838005246,x))

As it is a cubic equation with real coefficients, there cannot be three distinct complex roots. But it gives the following results.

[-3.19296319480108 - 0.e-22*I, 1.43925417946882 + 0.e-20*I, 6.95416726521169 - 0.e-20*I]

Could someone please tell me if something goes wrong. Is there other way to solve the equation and gives real roots?

Upvotes: 4

Views: 1923

Answers (1)

Nihal Sangeeth
Nihal Sangeeth

Reputation: 5515

There is a clear code level and interface level separation between solvers for equations in the complex domain and the real domain. For example solving 𝑒𝑥=1 when 𝑥 is to be solved in the complex domain, returns the set of all solutions, that is {2𝑛𝑖𝜋|𝑛∈ℤ}, whereas if 𝑥 is to be solved in the real domain then only {0} is returned.

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

Instead of solve() you should be using solveset()

from sympy import var, solveset
x = var('x', real=True)
print(solveset(-0.0643820896731566*x**3 + 0.334816369385245*x**2 + 1.08104426781115*x - 2.05750838005246,x))

{-3.19296319480108, 1.43925417946882, 6.95416726521169}

Upvotes: 4

Related Questions