Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate error for polynomial fitting (in slope and intercept)

Hi I want to calculate errors in slope and intercept which are calculated by scipy.polyfit function. I have (+/-) uncertainty for ydata so how can I include it for calculating uncertainty into slope and intercept? My code is,

from scipy import polyfit
import pylab as plt
from numpy import *

data = loadtxt("data.txt")
xdata,ydata = data[:,0],data[:,1]


x_d,y_d = log10(xdata),log10(ydata)
polycoef = polyfit(x_d, y_d, 1)
yfit = 10**( polycoef[0]*x_d+polycoef[1] )


plt.subplot(111)
plt.loglog(xdata,ydata,'.k',xdata,yfit,'-r')
plt.show()

Thanks a lot

like image 683
physics_for_all Avatar asked Oct 07 '22 11:10

physics_for_all


1 Answers

You could use scipy.optimize.curve_fit instead of polyfit. It has a parameter sigma for errors of ydata. If you have your error for every y value in a sequence yerror (so that yerror has the same length as your y_d sequence) you can do:

polycoef, _ = scipy.optimize.curve_fit(lambda x, a, b: a*x+b, x_d, y_d, sigma=yerror)

For an alternative see the paragraph Fitting a power-law to data with errors in the Scipy Cookbook.

like image 197
halex Avatar answered Oct 09 '22 02:10

halex