Reputation: 3
I would like to use a polynomial function of the type ax +bx^2+c*x^3+... to fit some data using scipy.optimize.curve_fit.
I managed to do it fine but my problem is that I would like the user to be able to enter the degree of the polynomial for the fit and nothing more. I haven't been able to find an easy way to generate a polynomial of degree n without specifying the coefficients in python. Can anyone help me?
Thanks!
Upvotes: 0
Views: 4830
Reputation: 18567
Yes, you can create an arbitrary degree polynomial, it will compute up to however many coefficients you give it. You want to make sure to give it d+1
coefficients if the user wants a polynomial of degree d
. You can convince curve_fit
to give it d+1
coefficients if you make sure the initial guess has length d+1
.
from scipy.optimize import curve_fit
# get xdata, ydata, and desired degree d from user
def arbitrary_poly(x, *params):
return sum([p*(x**i) for i, p in enumerate(params)])
popt, pcov = curve_fit(arbitrary_poly, xdata, ydata, p0=[1]*(d+1))
The [1]*(d+1)
is just one possible initial guess that has the correct length. If you're doing something smarter to pick the initial guess, you should do that, and you probably already have to make sure it has the correct length. If you're not figuring out your own p0
, curve_fit
defaults to an array of all 1s, assuming it can figure out the appropriate length. Since arbitrary_poly
is specifically designed to take any number of params, and hence will not allow curve_fit
to figure out what the expected length is, the default behaviour would raise an exception. That is fixed by giving it an explicit array of all 1s, of the right length.
Upvotes: 3