Forum Archive

SymPy factoring of polynomials

Sebastian

Hey guys, just a quick question.

I'm using SymPy to factorize polynomials, but I stumbled upon a certain polynomial that it wouldn't factorize.
I have P(x) = x**3 - 3*x, which should be factorized to x*(x-sqrt(3))*(x+sqrt(3)).
Using sympy.factor('x**3-3*x'), I get x*(x**2 - 3).

Any ideas why SymPy can't factorize this polynomial?

ccc

You should try to post this question to stackoverflow.com

JonB

Reading the help of factor shows that factor will only factor rationals, unless you tell it what extensions to use. sqrt(3) is not rational. You could generate such a list from roots, see below.

expr='(x**3-3*x)'
# find extensions needed for factor.
# of course, we could also simply use the roots directly and form a poly
# extension=True here lets it detect sqrt, etc 
r=set([abs(x) for x in list(roots(expr,extension=True).keys()) if not x==0])

f=factor(expr,extension=r,deep=True)
print(f)

I suspect it is also possible to directly take the output of roots, and generate a factored polynomial. I didnt see that in the docs, so this does it:

f=1
x=symbols('x')
for k,v in roots(expr,extension=True).items():
    f=f*(x-k)**v    
Sebastian

@JonB this is exactly what I'm looking for, thank you! Since I learned mathematics with Norwegian terms, I didn't really know what to search for in English 😂