Python中的有理函数曲线拟合

7

这不是一个推荐问题,而是在询问如何使用scipy在Python中实现它。 - Jason S
4
投票决定重新开启:关闭的理由扭曲了“不征求建议”的精神。如果我们采用这种观点,就必须关闭所有要求任何东西的问题,因为答案可能会推荐某些API等等。即使是“已关闭”的说明也说:“相反,请描述问题和已经采取的解决方法。” 这已经做到了。问题不是“告诉我一个好的开源CAS”,而是“在这个CAS中告诉我如何做XYZ”。 - Evgeni Sergeev
投票重新开放:这是一个问题:“如何在这种情况下使用scipy.optimize.curve_fit()?” - hynekcer
1个回答

9

您有一个函数,它是有理函数。因此,您需要设置该函数并执行拟合操作。由于curve_fit要求您以非列表的形式提供参数,因此我提供了一个额外的函数,用于在分子和分母中均为三次多项式的特定情况下进行拟合。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接