Overview
NumPy's polynomial package provides a modern, class-based API for handling power series. It replaces the legacy poly1d conventions with objects that handle domain scaling, root finding, and advanced orthogonal polynomials (Chebyshev, Legendre) for numerical stability.
When to Use
- Fitting a curve to noisy experimental data using least-squares.
- Finding the zeros (roots) of a mathematical function approximated by a polynomial.
- Performing high-precision function approximation using Chebyshev series.
- Computing integrals or derivatives of polynomial models.
Decision Tree
- Creating a new polynomial from coefficients?
- Use
Polynomial([c0, c1, c2]). Note: coefficients are in increasing degree.
- Use
- Fitting data?
- Use
Polynomial.fit(x, y, deg). It automatically scales the domain for stability.
- Use
- Need to evaluate the fit?
- Use the returned object directly:
p(x).
- Use the returned object directly:
Workflows
-
Stable Data Fitting
- Identify noisy data (x, y).
- Use
p = Polynomial.fit(x, y, deg=3)to find the best fit. - Evaluate the model over a range using
p.linspace()to visualize the result.
-
Polynomial Root Finding
- Define coefficients
[c0, c1, c2](constant, linear, quadratic). - Instantiate the polynomial:
p = Polynomial(coefs). - Call
p.roots()to find the values of x wherep(x) = 0.
- Define coefficients
-
Orthogonal Series Interpolation
- Import the
Chebyshevclass. - Use
Chebyshev.interpolate(func, deg)to create a series that matches a function at Chebyshev points. - Utilize the resulting object for high-precision function approximation.
- Import the
Non-Obvious Insights
- Increasing Degree: The modern API uses coefficients in order (0, 1, 2...), reversing the
poly1dconvention (highest degree first). This is a common source of bugs during migration. - Domain Scaling:
Polynomial.fit()maps the input $x$ values to a internal window (usually $[-1, 1]$). Evaluating usingp.convert().coefdirectly on raw $x$ values without scaling will fail; always use the class instancep(x). - Arithmetic Restrictions: Polynomials with different domain or window attributes cannot be mixed in arithmetic operations; they must be converted to a shared domain first.
Evidence
- "The various routines in numpy.polynomial all deal with series whose coefficients go from degree zero upward, which is the reverse order of the poly1d convention." Source
- "Polynomials with different domain and window attributes are not considered equal, and can’t be mixed in arithmetic." Source
Scripts
scripts/numpy-polynomial_tool.py: Implements curve fitting and root finding using the modern API.scripts/numpy-polynomial_tool.js: Simulated polynomial evaluator logic.
Dependencies
numpy(Python)