python中有理函数曲线拟合

2024-06-30 05:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用有理函数拟合X和Y数据点的曲线。它可以在Matlab中使用cftool(http://de.mathworks.com/help/curvefit/rational.html)来完成。但是,我希望在Python中也这样做。我试着用scipy.optimize.curve U拟合,但它最初需要一个函数,我没有。在


Tags: 数据comhttphtmlhelpdescipy曲线
1条回答
网友
1楼 · 发布于 2024-06-30 05:31:37

你有这个函数,它是有理函数。所以你需要设置函数并进行拟合。由于曲线拟合要求你提供参数而不是列表,我提供了一个附加函数,它对分子和分母的三次多项式的具体情况进行拟合。在

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 zeroth order coefficient of the denominator polynomial is fixed at 1.
    Numpy stores coefficients in [x**2 + x + 1] order, so the fixed
    zeroth order denominator coefficent must comes last. (Edited.)
    """
    return np.polyval(p, x) / np.polyval(q + [1.0], 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

相关问题 更多 >