We use polynomial operations to work with equations like lines or curves easily.
Using np.poly helps us find the polynomial from its roots, which is useful in math and data science.
0
0
Polynomial operations with np.poly in NumPy
Introduction
You have the roots (solutions) of a polynomial and want to find its equation.
You want to create a polynomial curve that passes through certain points.
You need to analyze or plot polynomial functions based on their roots.
You want to simplify polynomial expressions in data modeling.
Syntax
NumPy
numpy.poly(r)
# r is a sequence (list or array) of roots of the polynomialThe function returns the coefficients of the polynomial with the given roots.
Coefficients are in descending order of powers, starting with the highest degree.
Examples
This finds the polynomial coefficients for roots 1, 2, and 3.
NumPy
import numpy as np roots = [1, 2, 3] coefficients = np.poly(roots) print(coefficients)
Polynomial with roots 0 and -1 gives coefficients for x² + x.
NumPy
coeffs = np.poly([0, -1]) print(coeffs)
Sample Program
This program finds the polynomial coefficients from roots 2, 4, and 6. Then it checks the polynomial value at each root, which should be zero or very close.
NumPy
import numpy as np # Define roots of the polynomial roots = [2, 4, 6] # Get polynomial coefficients from roots coefficients = np.poly(roots) print('Polynomial coefficients:', coefficients) # To verify, evaluate polynomial at roots (should be close to zero) for r in roots: value = np.polyval(coefficients, r) print(f'P({r}) = {value}')
OutputSuccess
Important Notes
Roots can be real or complex numbers.
Polynomial coefficients are returned as a NumPy array.
Use np.polyval to evaluate the polynomial at any point.
Summary
np.poly creates polynomial coefficients from roots.
Coefficients start with the highest power term.
Use it to build polynomial equations easily from known roots.