Ignore Imaginary Roots In Sympy
Solution 1:
If you set x
to be real, SymPy will only give you the real solutions
x = Symbol('x', real=True)
solve(..., x)
Solution 2:
solve()
doesn’t have a consistent output for various types of solutions, please use 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)
Solution 3:
This is exactly the sort of thing that real_roots
is made for and is especially applicable to your case where the coefficients are integers:
x = Symbol('x')
eq = int(row["scaleA"])*x**3 + int(row["scaleB"])*x**2 + int(row["scaleC"])*x + int(row["scaleD"])
y = real_roots(eq, x) # gives [CRootOf(...), ...]
The value of CRootOf instances can be evaluated to whatever precision you need and should not contain any imaginary part. For example,
>>> [i.n(12) for i in real_roots(3*x**3 - 2*x**2 + 7*x - 9, x)]
[1.07951904858]
Note: As I recall, solve will send back roots that it wasn't able to confirm met the assumptions (i.e. if they weren't found to be false for the assumption then they are returned). Also, if you want more consistent output from solve, @PyRick, set the flag dict=True
.
Solution 4:
As Krastonov had mentioned mpmath provided an easier method:
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
Solution 5:
I managed to simply ignore solutions containing the character "I"
and used .evalf()
to evaluate the expression. The code is now:
x = Symbol('x')
y = solve(int(row["scaleA"])*x**3 + int(row["scaleB"])*x**2 + int(row["scaleC"])*x + int(row["scaleD"]), x)
for root in y:
if "I" not in str(root):
print("This One:" + str(root.evalf()))
Post a Comment for "Ignore Imaginary Roots In Sympy"