Python fit polynomial, power law and exponential from data
Posted
by
Nadir
on Stack Overflow
See other posts from Stack Overflow
or by Nadir
Published on 2014-06-08T09:15:43Z
Indexed on
2014/06/08
9:24 UTC
Read the original article
Hit count: 421
I have some data (x
and y
coordinates) coming from a study and I have to plot them and to find the best curve that fits data. My curves are:
- polynomial up to 6th degree;
- power law; and
- exponential.
I am able to find the best fit for polynomial with
while(i < 6):
coefs, val = poly.polyfit(x, y, i, full=True)
and I take the degree that minimizes val
.
When I have to fit a power law (the most probable in my study), I do not know how to do it correctly. This is what I have done. I have applied the log function to all x
and y
and I have tried to fit it with a linear polynomial. If the error (val) is lower than the others polynomial tried before, I have chosen the power law function. Am I correct?
Now how can I reconstruct my power law starting from the line y = mx + q
in order to draw it with the original points? I need also to display the function found.
I have tried with:
def power_law(x, m, q):
return q * (x**m)
using
x_new = np.linspace(x[0], x[-1], num=len(x)*10)
y1 = power_law(x_new, coefs[0], coefs[1])
popt, pcov = curve_fit(power_law, x_new, y1)
but it seems not to work well.
© Stack Overflow or respective owner