Generate a monic polynomial with given complex roots in Python

To generate a monic polynomial with given complex roots, use the polynomial.polyfromroots() method in Python NumPy. The method returns a 1-D array of the polynomial's coefficients. If all the roots are real, then the output is also real, otherwise it is complex. The parameter roots is the sequence containing the roots.

Syntax

numpy.polynomial.polynomial.polyfromroots(roots)

Parameters

  • roots ? Sequence containing the roots of the polynomial

Return Value

Returns a 1-D array of polynomial coefficients ordered from low to high degree.

Example with Complex Roots

Let's generate a monic polynomial with complex roots +i and -i ?

from numpy.polynomial import polynomial as P
import numpy as np

# Define complex roots +i and -i
j = complex(0, 1)
roots = [-j, j]

# Generate the monic polynomial
coefficients = P.polyfromroots(roots)
print("Complex roots:", roots)
print("Polynomial coefficients:", coefficients)
print("Data type:", coefficients.dtype)
print("Shape:", coefficients.shape)
Complex roots: [(-0-1j), 1j]
Polynomial coefficients: [1.+0.j 0.+0.j 1.+0.j]
Data type: complex128
Shape: (3,)

Example with Real Roots

When all roots are real, the output coefficients are also real ?

from numpy.polynomial import polynomial as P

# Define real roots
real_roots = [2, -3, 1]

# Generate the monic polynomial
coefficients = P.polyfromroots(real_roots)
print("Real roots:", real_roots)
print("Polynomial coefficients:", coefficients)
print("Data type:", coefficients.dtype)
Real roots: [2, -3, 1]
Polynomial coefficients: [-6.  0.  2.  1.]
Data type: float64

How It Works

The polynomial with roots r?, r?, ..., r? has the form:

(x - r?)(x - r?)...(x - r?)

For roots +i and -i, the polynomial becomes:

(x - i)(x + i) = x² + 1

The coefficients [1, 0, 1] represent: 1 + 0x + 1x² = x² + 1

Conclusion

Use numpy.polynomial.polynomial.polyfromroots() to generate monic polynomials from given roots. The function automatically handles both real and complex roots, returning appropriate coefficient data types.

Updated on: 2026-03-26T20:54:38+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements