Written and maintained by CASRAI Editorial Board
Last updated
numpy.polyfit(x, y, deg) fits a polynomial of degree deg to data by least squares and returns the coefficients, highest power first. This guide is for researchers and analysts who need to run the fit, read its diagnostics and report it, and who need to know that NumPy now treats this function as legacy in favour of numpy.polynomial.Polynomial.fit.
What numpy.polyfit is used for in research
It is used to describe a curved trend in measured data, such as a calibration curve, a dose or growth trend, or a drift correction, with a low-degree polynomial. Per the NumPy reference (read 2026-11-08), it returns the coefficients p of p[0]*x**deg + ... + p[deg] that minimise the squared error. For the model forms behind it, see our guides to quadratic regression and cubic regression. The same task in MATLAB is covered in Fit in MATLAB: polyfit, fit and fittype.
Install or access
numpy.polyfit ships with NumPy. Install NumPy from the official project with pip install numpy (see numpy.org/install for conda and other routes), then use import numpy as np. No separate package is needed.
Syntax and arguments
The documented signature is numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False).
| Argument | What it does (NumPy reference, read 2026-11-08) |
|---|---|
x |
Sample x-coordinates, shape (M,). |
y |
Sample y-coordinates, shape (M,) or (M, K). A 2-D y fits several datasets that share the same x; the k-th set of coefficients is in p[:, k]. |
deg |
Integer degree of the fitting polynomial. |
rcond |
Relative condition number: singular values smaller than this, relative to the largest, are ignored. Default is len(x)*eps. |
full |
If False (default) only the coefficients are returned; if True the residuals, rank, singular values and rcond are returned as well. |
w |
Weights applied to the unsquared residuals y[i] - y_hat[i]. For inverse-variance weighting use w[i] = 1/sigma(y[i]). |
cov |
If not False, also returns the covariance matrix of the coefficient estimates (only when full=False), scaled by chi2/dof with dof = M – (deg + 1). cov='unscaled' omits the scaling, intended for w = 1/sigma when the sigmas are reliable. |
Step-by-step: fit, evaluate and plot a polynomial
- Put the data in two equal-length arrays. This is the example from the NumPy documentation:
x = np.array([0, 1, 2, 3, 4, 5])andy = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]). - Fit a cubic:
z = np.polyfit(x, y, 3). The result isarray([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]), i.e. 0.0870x³ – 0.8135x² + 1.6931x – 0.0397. - Wrap the coefficients so they can be evaluated:
p = np.poly1d(z), thenp(0.5)gives about 0.61438 (the documented value is 0.6143849206349179; the last digits vary by platform). - Alternatively evaluate without
poly1d:np.polyval(z, x_new). - To plot the curve, evaluate on a fine grid such as
xs = np.linspace(0, 5, 200)and plotp(xs)over the observed points with matplotlib.
Output and how to read it
Coefficient order
The array runs from the highest power to the constant term. numpy.polynomial classes use the opposite order, lowest degree first, so reversing is needed when moving between them.
Fit diagnostics with full=True
With c, resid, rank, sv, rcond = np.polyfit(x, y, 3, full=True) on the example data, run under NumPy 2.5.1 (our own run, 2026-11-08), the sum of squared residuals is 0.0397, the rank is 4 and the four singular values range from 1.88 down to 0.027. A rank lower than deg + 1 means the fit is rank deficient.
Coefficient uncertainty with cov=True
p, V = np.polyfit(x, y, 2, cov=True) returns a (deg+1, deg+1) covariance matrix whose diagonal holds the coefficient variances. On the example data (our own run) the quadratic coefficients are -0.1607, 0.5007 and 0.2214, with standard errors np.sqrt(np.diag(V)) of 0.069, 0.359 and 0.381. Because the scaling uses M – (deg + 1) degrees of freedom, you need more points than coefficients.
R-squared is not returned
The function does not report R². You can compute it yourself from the fitted values: ss_res = ((y - np.polyval(fit, x))**2).sum(), ss_tot = ((y - y.mean())**2).sum(), 1 - ss_res/ss_tot. For the quadratic fit above this gives 0.829 in our own calculation (not a NumPy-documented output). See the coefficient of determination formula and how to calculate residuals; a high R² from a high-degree polynomial says little, as explained in what is overfitting.
polyfit is legacy: moving to Polynomial.fit
The NumPy documentation states that poly1d and functions in numpy.lib.polynomial, including numpy.polyfit, are considered legacy and should not be used in new code; since NumPy 1.4 the numpy.polynomial package is preferred, and Polynomial.fit is recommended as more numerically stable. It still works, so existing analysis scripts do not break.
from numpy.polynomial import Polynomial
P = Polynomial.fit(x, y, deg=3)
P(0.5) # evaluate in original x units
P.convert().coef # coefficients in original units, lowest degree first
Three things differ. Coefficients run lowest degree first. Polynomial.fit maps the data onto a scaled window (here domain [0, 5] to window [-1, 1] in our run), so the raw P.coef are in scaled units; call .convert() to get coefficients in the original data units. On the example data P.convert().coef is [-0.03968254, 1.69312169, -0.81349206, 0.08703704], the same numbers as polyfit in reverse order, and P(0.5) matches p(0.5). Finally, polynomials with different domain or window cannot be combined and raise TypeError: Domains differ.
Troubleshooting
RankWarning: Polyfit may be poorly conditioned
NumPy documents that the Vandermonde matrix is inherently badly conditioned when the degree is large or the sample interval is badly centred. The documented remedies are to lower the degree or to replace x by x - x.mean(). Lowering rcond may give a spurious fit. The warning is only raised when full=False. On the 6-point example, asking for degree 6 triggers it in our run, since seven coefficients cannot be determined from six points. To silence it deliberately: warnings.simplefilter('ignore', np.exceptions.RankWarning), but only after you understand why it fired.
Wrong or reversed coefficients
Check the order: polyfit and poly1d are highest-power first; numpy.polynomial is lowest first. Passing Polynomial.fit coefficients to np.polyval without .convert() gives wrong values.
Wild behaviour between or beyond the data
High-degree polynomials can fit noise and oscillate. The NumPy notes suggest splines as an alternative when a polynomial is a poor model.
Free alternatives
| Option | Relationship to numpy.polyfit |
|---|---|
numpy.polynomial.Polynomial.fit |
NumPy’s preferred, more stable replacement, same package. |
MATLAB polyfit |
Equivalent task in MATLAB; see Fit in MATLAB. |
| Splines | Named in the NumPy notes as an alternative to a single high-degree polynomial. |
FAQ
Which order does numpy.polyfit return coefficients in?
Highest power first: p[0]*x**deg + ... + p[deg].
Is numpy.polyfit deprecated?
NumPy calls it legacy and says it should not be used in new code, preferring numpy.polynomial.Polynomial.fit. The documentation does not describe a removal date.
How do I get R-squared from numpy.polyfit?
It is not returned. Compute it from the residuals as shown above, or request full=True to get the sum of squared residuals.
How do I get coefficient standard errors?
Use cov=True and take the square root of the diagonal of the returned covariance matrix.
How do I weight points by measurement error?
Pass w = 1/sigma, where sigma is the standard deviation of each y; weights apply to the unsquared residuals.
Sources
- NumPy reference, numpy.polyfit, read 2026-11-08.
- NumPy reference, Polynomials, read 2026-11-08.
- NumPy, Installing NumPy.
Numbers marked as our own run were computed with NumPy 2.5.1 on 2026-11-08.







