【问题标题】:Rational function curve fitting in pythonpython中的有理函数曲线拟合
【发布时间】:2015-07-01 03:29:47
【问题描述】:

我正在尝试使用有理函数将曲线拟合到 X 和 Y 数据点。可以使用 cftool (http://de.mathworks.com/help/curvefit/rational.html) 在 Matlab 中完成。但是,我希望在 Python 中做同样的事情。我曾尝试使用 scipy.optimize.curve_fit(),但它最初需要一个我没有的功能。

【问题讨论】:

  • 这不是一个推荐问题,它是在询问如何使用 scipy 在 Python 中做到这一点。
  • 投票重新开放:所述关闭原因是对“不征求建议”精神的歪曲。如果我们使用这种观点,我们将不得不关闭所有提出任何要求的问题,因为答案可能推荐某些 API 等。即使是“关闭”的宣传语也说“相反,描述问题以及什么到目前为止已经完成了解决它。”,这已经完成了。问题的形式不是“告诉我什么是好的开源 CAS”,而是“这是一个 CAS,告诉我如何在其中做 XYZ”。
  • 投票重新开放:这是一个问题:“在这种情况下如何使用 scipy.optimize.curve_fit()?”

标签: python matlab scipy curve-fitting


【解决方案1】:

你有函数,它是有理函数。因此,您需要设置功能并执行拟合。由于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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2022-01-13
    • 2019-03-25
    • 2018-10-07
    • 2020-12-06
    • 2018-04-03
    • 2018-11-13
    相关资源
    最近更新 更多