1

I have a question about the Python curve fitting, I know there's polyfit function in numpy, but if I assign the polynomial as AX^4 + BX^2, how to find this A and B???

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 4)  <---?
f = np.poly1d(z)         <---?   

Could someone give a hint??? Thank you!

okeyla
  • 65
  • 9

1 Answers1

1

You could try with leastsquares. Basically find values A and B so that the sum of residuals squared would be minimal. I have used scipy for that.

Here is my code:

import numpy as np
from scipy.optimize import leastsq
# --------------------------------
import matplotlib as mpl
mpl.rcParams['font.size']=20
import matplotlib.pyplot as plt
# -------------------------------------
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
#z = np.polyfit(x, y, 4)  <---?
#f = np.poly1d(z)         <---?   
# ----------------------------------------------
def poly(p,x):
    return p[0]*x**4+p[1]*x**2

def res(p,x,y):
    return y-poly(p,x)
# ----------------------------------------------
p0=[1.,1.];
pars=leastsq(res,p0,(x,y));
print pars[0]
# -----------------------------------------------
xi=np.linspace(np.min(x),np.max(x),100);

fig = plt.figure(figsize=(6,6));ax=fig.add_subplot(111);
ax.plot(x,y,ms=10,color='k',ls='none',marker='.');
ax.plot(xi,poly(pars[0],xi),color='0.8',lw=2.0);
plt.savefig('fit_result.png');
plt.show();
msi_gerva
  • 2,021
  • 3
  • 22
  • 28