I'm trying to fit a histogram with some data in it using scipy.optimize.curve_fit
. If I want to add an error in y
, I can simply do so by applying a weight
to the fit. But how to apply the error in x
(i. e. the error due to binning in case of histograms)?
My question also applies to errors in x
when making a linear regression with curve_fit
or polyfit
; I know how to add errors in y
, but not in x
.
Here an example (partly from the matplotlib documentation):
import numpy as np
import pylab as P
from scipy.optimize import curve_fit
# create the data histogram
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
# define fit function
def gauss(x, *p):
A, mu, sigma = p
return A*np.exp(-(x-mu)**2/(2*sigma**2))
# the histogram of the data
n, bins, patches = P.hist(x, 50, histtype='step')
sigma_n = np.sqrt(n) # Adding Poisson errors in y
bin_centres = (bins[:-1] + bins[1:])/2
sigma_x = (bins[1] - bins[0])/np.sqrt(12) # Binning error in x
P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
# fitting and plotting
p0 = [700, 200, 25]
popt, pcov = curve_fit(gauss, bin_centres, n, p0=p0, sigma=sigma_n, absolute_sigma=True)
x = np.arange(100, 300, 0.5)
fit = gauss(x, *popt)
P.plot(x, fit, 'r--')
Now, this fit (when it doesn't fail) does consider the y-errors sigma_n
, but I haven't found a way to make it consider sigma_x
. I scanned a couple of threads on the scipy mailing list and found out how to use the absolute_sigma
value and a post on Stackoverflow about asymmetrical errors, but nothing about errors in both directions. Is it possible to achieve?