# Scaling residual function with uncertainties in data

Reading over the docs for lmfit (https://lmfit.github.io/lmfit-py/fitting.html), specifically the "Goodness of Fit Statistics" section states the following:

"Note that the calculation of chi-square and reduced chi-square assume that the returned residual function is scaled properly to the uncertainties in the data. For these statistics to be meaningful, the person writing the function to be minimized must scale them properly."

I have calculated measurement uncertainties for my data points and but I'm not sure how to "scale" my residual function with my measurement uncertainty. My guess is to divide the error by the uncertainty seen in the for loop but this results in a large chi squared value which seems incorrect.

def residual(p):
v = p.valuesdict()
err = measurement * np.square(v['x0'] - x_det[:,0]) + np.square(v['y0'] - x_det[:,1])-v['Amp']
for idx,sigma in enumerate(meas_uncertainty):
err[idx] =  np.square(err[idx])/(sigma)
return err


I found additional documentation(http://cars9.uchicago.edu/software/python/lmfit/lmfit.pdf) that specifies the correct way to incorporate measurement error(weighting) into the least squares model. From the text:

In a traditional non-linear fit, one writes an objective function that takes the variable values and calculates the residual array $$y_i^{meas} − y_i^{model}(v)$$, or the residual array scaled by the data uncertainties($$ε_i$$), $$\frac{y_i^{meas} − y_i^{model}(v)}{ε_i}$$ , or some other weighting factor.

A code example from the text:

def residual(vars, x, data, eps_data):
amp = vars[0]
phaseshift = vars[1]
freq = vars[2]
decay = vars[3]
model = amp * sin(x*freq + phaseshift) * exp(-x*x*decay)
return (data-model) / eps_data