Finding a rational function in python

I am trying to fit a curve to data points X and Y using a rational function. This can be done in Matlab using cftool ( ). However, I want to do the same in Python. I tried using scipy.optimize.curve_fit, but initially it requires a function that I don't have.


source to share

1 answer

You have a function, it is a rational function. Therefore, you need to set up the function and complete the fitting. Since curve_fit requires you to supply your arguments other than lists, I have provided an additional function that sets the fitting on the specific case of the third degree polynomial in both the numerator and denominator.

def rational(x, p, q):
    The general rational function description.
    p is a list with the polynomial coefficients in the numerator
    q is a list with the polynomial coefficients (except the first one)
    in the denominator
    The first coefficient of the denominator polynomial is fixed at 1.
    return np.polyval(p, x) / np.polyval([1] + q, x)

def rational3_3(x, p0, p1, p2, q1, q2):
    return rational(x, [p0, p1, p2], [q1, q2])

x = np.linspace(0, 10, 100)  
y = rational(x, [-0.2, 0.3, 0.5], [-1.0, 2.0])
ynoise = y * (1.0 + np.random.normal(scale=0.1, size=x.shape))
popt, pcov = curve_fit(rational3_3, x, ynoise, p0=(0.2, 0.3, 0.5, -1.0, 2.0))
print popt

plt.plot(x, y, label='original')
plt.plot(x, ynoise, '.', label='data')
plt.plot(x, rational3_3(x, *popt), label='fit')


enter image description here



All Articles