There is already a function for that, np.polyfit:
fit = np.polyfit(x, y, n)
On the other hand, your func
does not have a constant term. Is that on purpose?
If you wish to write your own polyfit
-type method, you might want to study the source code for np.polyfit. You'll see that the problem is set up as a linear matrix equation and solved with np.linalg.lstsq, rather than the more general-purpose scipy.optimize.curve_fit
.
# set up least squares equation for powers of x
lhs = vander(x, order)
rhs = y
c, resids, rank, s = lstsq(lhs, rhs, rcond)
Useful reference:
- np.vander -- aha, this can be used to evaluate the polynomial at x. If you want to eliminate the constant term, you'd have to chop off the right-most column returned by
np.vander
.