Get the coefficients of a polynomial with Numpy

Viewed 1673

I'm trying to get the coefficients of a numpy.polynomial.polynomial.Polynomial obtained via the fit method:

import numpy.polynomial as poly

x = [1, 2, 3, 4, 5]
y = [16, 42.25, 81, 132.25, 196]

c = poly.Polynomial.fit(x, y, deg = 2)
print(c(5))
print(c)

This small program prints

196.00000000000006
poly([81. 90. 25.])

which is the correct value for c(5) but not for the polynomial coefficients, which are 2.25, 7.5, and 6.25. How do I get the actual coefficients?

1 Answers

Per documentation, the .fit() method returns

A series that represents the least squares fit to the data and has the domain and window specified in the call. If the coefficients for the unscaled and unshifted basis polynomials are of interest, do new_series.convert().coef.

Running c.convert().coef on your data produces:

array([2.25, 7.5 , 6.25])

Related