Movatterモバイル変換


[0]ホーム

URL:


SciPy

numpy.polyfit

numpy.polyfit(x,y,deg,rcond=None,full=False,w=None,cov=False)[source]

Least squares polynomial fit.

Fit a polynomialp(x)=p[0]*x**deg+...+p[deg] of degreedegto points(x, y). Returns a vector of coefficientsp that minimisesthe squared error.

Parameters:
x:array_like, shape (M,)

x-coordinates of the M sample points(x[i],y[i]).

y:array_like, shape (M,) or (M, K)

y-coordinates of the sample points. Several data sets of samplepoints sharing the same x-coordinates can be fitted at once bypassing in a 2D-array that contains one dataset per column.

deg:int

Degree of the fitting polynomial

rcond:float, optional

Relative condition number of the fit. Singular values smaller thanthis relative to the largest singular value will be ignored. Thedefault value is len(x)*eps, where eps is the relative precision ofthe float type, about 2e-16 in most cases.

full:bool, optional

Switch determining nature of return value. When it is False (thedefault) just the coefficients are returned, when True diagnosticinformation from the singular value decomposition is also returned.

w:array_like, shape (M,), optional

Weights to apply to the y-coordinates of the sample points. Forgaussian uncertainties, use 1/sigma (not 1/sigma**2).

cov:bool, optional

Return the estimate and the covariance matrix of the estimateIf full is True, then cov is not returned.

Returns:
p:ndarray, shape (deg + 1,) or (deg + 1, K)

Polynomial coefficients, highest power first. Ify was 2-D, thecoefficients fork-th data set are inp[:,k].

residuals, rank, singular_values, rcond

Present only iffull = True. Residuals of the least-squares fit,the effective rank of the scaled Vandermonde coefficient matrix,its singular values, and the specified value ofrcond. For moredetails, seelinalg.lstsq.

V:ndarray, shape (M,M) or (M,M,K)

Present only iffull = False andcov`=True. The covariancematrix of the polynomial coefficient estimates. The diagonal ofthis matrix are the variance estimates for each coefficient. If yis a 2-D array, then the covariance matrix for the `k-th data setare inV[:,:,k]

Warns:
RankWarning

The rank of the coefficient matrix in the least-squares fit isdeficient. The warning is only raised iffull = False.

The warnings can be turned off by

>>>importwarnings>>>warnings.simplefilter('ignore',np.RankWarning)

See also

polyval
Compute polynomial values.
linalg.lstsq
Computes a least-squares fit.
scipy.interpolate.UnivariateSpline
Computes spline fits.

Notes

The solution minimizes the squared error

E = \sum_{j=0}^k |p(x_j) - y_j|^2

in the equations:

x[0]**n*p[0]+...+x[0]*p[n-1]+p[n]=y[0]x[1]**n*p[0]+...+x[1]*p[n-1]+p[n]=y[1]...x[k]**n*p[0]+...+x[k]*p[n-1]+p[n]=y[k]

The coefficient matrix of the coefficientsp is a Vandermonde matrix.

polyfit issues aRankWarning when the least-squares fit is badlyconditioned. This implies that the best fit is not well-defined dueto numerical error. The results may be improved by lowering the polynomialdegree or by replacingx byx -x.mean(). Thercond parametercan also be set to a value smaller than its default, but the resultingfit may be spurious: including contributions from the small singularvalues can add numerical noise to the result.

Note that fitting polynomial coefficients is inherently badly conditionedwhen the degree of the polynomial is large or the interval of sample pointsis badly centered. The quality of the fit should always be checked in thesecases. When polynomial fits are not satisfactory, splines may be a goodalternative.

References

[1]Wikipedia, “Curve fitting”,http://en.wikipedia.org/wiki/Curve_fitting
[2]Wikipedia, “Polynomial interpolation”,http://en.wikipedia.org/wiki/Polynomial_interpolation

Examples

>>>x=np.array([0.0,1.0,2.0,3.0,4.0,5.0])>>>y=np.array([0.0,0.8,0.9,0.1,-0.8,-1.0])>>>z=np.polyfit(x,y,3)>>>zarray([ 0.08703704, -0.81349206,  1.69312169, -0.03968254])

It is convenient to usepoly1d objects for dealing with polynomials:

>>>p=np.poly1d(z)>>>p(0.5)0.6143849206349179>>>p(3.5)-0.34732142857143039>>>p(10)22.579365079365115

High-order polynomials may oscillate wildly:

>>>p30=np.poly1d(np.polyfit(x,y,30))/... RankWarning: Polyfit may be poorly conditioned...>>>p30(4)-0.80000000000000204>>>p30(5)-0.99999999999999445>>>p30(4.5)-0.10547061179440398

Illustration:

>>>importmatplotlib.pyplotasplt>>>xp=np.linspace(-2,6,100)>>>_=plt.plot(x,y,'.',xp,p(xp),'-',xp,p30(xp),'--')>>>plt.ylim(-2,2)(-2, 2)>>>plt.show()
../../_images/numpy-polyfit-1.png

Previous topic

numpy.roots

Next topic

numpy.polyder

Quick search

  • © Copyright 2008-2018, The SciPy community.
  • Last updated on Jul 24, 2018.
  • Created usingSphinx 1.6.6.

[8]ページ先頭

©2009-2025 Movatter.jp