Fit a Function

David McIntyre
11 January 2018

Initialization

SetOptions[Plot,AxesStyle->Directive[FontFamily->"Arial",FontSize->14,Black,AbsoluteThickness[0.5],Arrowheads[0.04]],PlotStyle->{{Black,AbsoluteThickness[2]}},TicksStyle->{{Black,AbsoluteThickness[0.5]},{Black,AbsoluteThickness[0.5]}},PlotRange->All];

SetOptions[ListPlot,AxesStyle->Directive[FontFamily->"Arial",FontSize->14,Black,AbsoluteThickness[0.5],Arrowheads[0.04]],PlotStyle->{{Black,AbsoluteThickness[2]}},TicksStyle->{{Black,AbsoluteThickness[0.5]},{Black,AbsoluteThickness[0.5]}},AxesLabel->{"Frequency (Hz)","Signal (Arb)"},PlotRange->All,ImageSize->600];

ctrl-9 to start inline formula and ctrl-0 to end. ctrl-_ to begin subscript, ctrl-space to end. esc-alpha-esc to enter Greek letters.

Fitting

Data.  Enter data here.  The data is entered as a list of pairs of data points.  Each pair comprises the independent variable (x) and the dependent variable (y).

data={{1,0.10},{2,0.15},{3,0.20},{4,0.04},{5,0.40},{6,0.68},{7,0.81},{8,1.47},{9,2.38},{10,5.03},{11,2.02},{12,1.18},{13,0.69},{14,0.35},{15,0.51},{16,0.01},{17,0.16},{18,0.35},{19,0.50},{20,0.05}}

dataplot=ListPlot[data]

Fit data to Lorentzian function
S(f)=(A/((((f-f0))^2)+(df^2)))
with amplitude A, center frequency f0, full width at half maximum (FWHM) df.  Because this function has a nonlinear dependence on some of the parameters, we must use the Nonlinear fitting function. The default is that the fit starts by assuming the parameters are 1  and then searches from there.  It is best if you enter some more accurate starting values.

fit=NonlinearModelFit[data,A/((((f-f0))^2)+(((df/2))^2)),{{A,4},{f0,9},{df,3}},f]

fit["ParameterTable"]

This says that our fit parameters are
A = 5.43 ± 0.65
f0 = 9.93 ± 0.07
df = 2.11 ± 0.15
This is close to the expected values of A=5, f0=10, df=2  that I used to make up the data (with noise added) and the same as I got with Excel.

Plot fit and compare to data

theoryplot=Plot[fit[f],{f,0,20}]

Show[dataplot,theoryplot]

Chi Squared value is buried in this table.  It is  (χ^2) = 1.1173, just as we found in Excel (small deviation because I used less precision in data here)

fit["ANOVATable"]