Search code examples
pythoncurve-fittingdata-fittingscipy-optimize

Problem Data Fitting with Square Root function


I try to fit this experimental data with a square root function, using python and the module scipy.optimize. The code for plotting and fitting looks like this.

def curve(x, a, b): 
    return np.sqrt(a+b*x)

xaxis = np.linspace(30, 1400, 10000)
farbe = ['tab:green', 'tab:orange', 'tab:blue']
fill = ['left', 'top', 'none']

k = 0
for i in data: 
    popt, pcov = curve_fit(curve, data[i].velo, data[i].avgFR)

    plt.errorbar(data[i].velo, data[i].avgFR,data[i].avgFRError, xerr=None, 
                  fmt="o", fillstyle = fill[k],alpha = 0.9,markersize=8,
                  markeredgewidth=2,
                  linewidth=3,   # width of plot line
                  elinewidth=2,# width of error bar line
                  capsize=5,     # cap length for error bar
                  capthick=1,   # cap thickness for error bar
                  label = str(i), 
                  color = farbe[k])   
    plt.plot(xaxis, curve(xaxis, *popt),color = farbe[k], linewidth = 3)
    k += 1

#plt.xscale('log')
plt.legend()
plt.show()

If i execute the script the fit looks like this. What is going wrong? Is there a better way to fit my data with a square root function?

Edit: I get the following message:

__main__:2: RuntimeWarning: invalid value encountered in sqrt
__main__:2: RuntimeWarning: invalid value encountered in sqrt
__main__:2: RuntimeWarning: invalid value encountered in sqrt

Solution

  • I know it is not the most elegant solution, but at least it works. Instead of fitting the sqrt data i descided to calculate the square of the data and fit it with a linear function the result it self looks decent.