'Find all roots of a polynomial with sympy
As an example, I want to find all five roots of the polynomial x**3 * (x - 3)**2
.
sympy's solve
command finds a 0
and a 3
:
from sympy import *
x = symbols ('x')
solve (x**3 * (x - 3)**2)
[0, 3]
According to the fundamental theorem of algebra, I would have hoped that solve
honored the multiplicity of the roots and returned something like
[0, 0, 0, 3, 3]
Unfortunately, I could not find any parameter that would persuade solve
or other solvers like solveset
, nonlinsolve
, and nsolve
to return a list of five elements. Fortunately, sympy's roots
returns a dictionary indicating the multiplicity:
r = roots (x**3 * (x - 3)**2); r
{3: 2, 0: 3}
Is there an easy way to transform this dictionary into the desired list of five elements? I came up with
l = []
for k, v in r.items ():
for m in range (v):
l.append (k)
l
[3, 3, 0, 0, 0]
but I feel like there should be a more elegant way ...
Solution 1:[1]
Use the multiple
argument to roots
:
In [91]: roots(x**3 * (x - 3)**2)
Out[91]: {0: 3, 3: 2}
In [92]: roots(x**3 * (x - 3)**2, multiple=True)
Out[92]: [0, 0, 0, 3, 3]
https://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.polyroots.roots
Solution 2:[2]
A slightly more elegant solution:
a = []
[a.extend([k]*v) for k, v in r.items()]
print(a)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oscar Benjamin |
Solution 2 | QWERTYL |