# Compute the roots of a polynomial with given complex roots in Python

PythonNumpyServer Side ProgrammingProgramming

To compute the roots of a polynomials, use the polynomial.polyroots() method in Python Numpy. The method returns an array of the roots of the polynomial. If all the roots are real, then out is also real, otherwise it is complex. The parameter, c is a 1-D array of polynomial coefficients.

The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the power series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton’s method.

## Steps

At first, import the required libraries-

from numpy.polynomial import polynomial as P

To compute the roots of a polynomials, use the polynomial.polyroots() method in Python Numpy −

j = complex(0,1)
print("Result (roots of a polynomial)...\n",P.polyroots((-j,j)))

Get the datatype −

print("\nType...\n",P.polyroots((-j, j)).dtype)

Get the shape −

print("\nShape...\n",P.polyroots((-j, j)).shape)

## Example

from numpy.polynomial import polynomial as P

# To compute the roots of a polynomials, use the polynomial.polyroots() method in Python Numpy.
# The method returns an array of the roots of the polynomial. If all the roots are real, then out is also real, otherwise it is complex.

# The parameter, c is a 1-D array of polynomial coefficients.
j = complex(0,1)
print("Result (roots of a polynomial)...\n",P.polyroots((-j,j)))

# Get the datatype
print("\nType...\n",P.polyroots((-j, j)).dtype)

# Get the shape
print("\nShape...\n",P.polyroots((-j, j)).shape)

## Output

Result (roots of a polynomial)...
[1.+0.j]

Type...
complex128

Shape...
(1,)
Updated on 08-Mar-2022 06:25:40

Advertisements