Exponential curve fitting in SciPy

后端 未结 2 1947
执笔经年
执笔经年 2020-12-05 04:40

I have two NumPy arrays x and y. When I try to fit my data using exponential function and curve_fit (SciPy) with this simple code

2条回答
  •  無奈伤痛
    2020-12-05 05:21

    Firstly I would recommend modifying your equation to a*np.exp(-c*(x-b))+d, otherwise the exponential will always be centered on x=0 which may not always be the case. You also need to specify reasonable initial conditions (the 4th argument to curve_fit specifies initial conditions for [a,b,c,d]).

    This code fits nicely:

    from pylab import *
    from scipy.optimize import curve_fit
    
    x = np.array([399.75, 989.25, 1578.75, 2168.25, 2757.75, 3347.25, 3936.75, 4526.25, 5115.75, 5705.25])
    y = np.array([109,62,39,13,10,4,2,0,1,2])
    
    def func(x, a, b, c, d):
        return a*np.exp(-c*(x-b))+d
    
    popt, pcov = curve_fit(func, x, y, [100,400,0.001,0])
    print popt
    
    plot(x,y)
    x=linspace(400,6000,10000)
    plot(x,func(x,*popt))
    show()
    

提交回复
热议问题