【问题标题】:Curve fitting using scipy with backward dependency使用具有向后依赖关系的 scipy 进行曲线拟合
【发布时间】:2026-02-22 22:45:01
【问题描述】:

我正在尝试对瞬态热数据进行曲线拟合。我有方程可以计算每个时间点的温度增量。必须将此增量添加到前一个时间点的温度中才能获得任何给定时间点的温度。

即; Tn = Tn-1 + delta.

如果我使用 scipy 文档中的example 来表达curve_fit。应该是类似的。

def func(x, a, b, c):
    return a * np.exp(-b * x) + c #+ func(x[n-1], a, b, c) <<< need help here

xdata = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3, 0.5)
np.random.seed(1729)
y_noise = 0.2 * np.random.normal(size=xdata.size)
ydata = y + y_noise
popt, pcov = curve_fit(func, xdata, ydata)
print(popt)
plt.plot(xdata, ydata, 'b-', label='data')
plt.plot(xdata, func(xdata, *popt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

非常感谢任何有关如何实现这一目标的线索。谢谢!

【问题讨论】:

    标签: python scipy curve-fitting


    【解决方案1】:

    如果您有一个微分方程,您需要在将其拟合到数据之前找到积分。除非数据也是差分的,在这种情况下你可以拟合。

    问题似乎暗示在您的情况下deltaa * np.exp(-b * x) + c 给出,这使得生成的y 值易于计算,因为curve_fit 将x 值全部传递给@987654325 @ 并希望它返回 all y 值。

    def delta_func(x, a, b, c):
        return a * np.exp(-b * x) + c
    
    def func(x, a, b, c):
        y = np.empty(x.shape)
        y[0] = delta_func(0, a, b, c)
        for i in range(1, len(x)):
            y[i] = y[i-1] + delta_func(x[i], a, b, c)
        return y
    

    这是为了说明。您可以使用np.cumsum 获得相同的结果:

    def func(x, a, b, c):
        return np.cumsum(a * np.exp(-b * x) + c)
    

    【讨论】: