Pure functions. LinearModelFit

Pure functions: when a function is needed in a very limited scope.

Function[x,x^2] (* First parameter is the anonymous variable, which is transformed according the second *)

%[a+b]

Now, with runes

#^2& (* #, equivalent to #1, is the parameter, therefore it is already in the place of the argument - the ampersand &  tells the program that it is a pure function *)

%[a+b]

Selecting values of a list

a bigger test list for this function

testList=RandomVariate[NormalDistribution[10,4],1000];

Select[testList,#<0&]

Select[testList, 0.5<#<1&]

LinearModelFit

An example with Angular Distribution

Experimental data

xws={{0,1.17,0.12},{0.5236,1.43,0.11},{1.0472,1.16,0.09},{1.5708,0.5,0.07},{2.0944,0.95,0.09},{2.6180,1.38,0.11},{3.141592653589793,0.96,0.12}}

xw=xws[[All,{1,2}]]

σ=xws[[All,3]]

Needs["ErrorBarPlots`"]

wDataPlot=ErrorListPlot[xws,AxesLabel->{"θ (rd)","W"}]

Fit: first unweighted, then using the variances

aUnweightedFit=LinearModelFit[xw,{LegendreP[2,Cos[θ]],LegendreP[4,Cos[θ]]},{θ}]

aUnweightedFit["ParameterTable"]

aUwFitPlot=Plot[aUnweightedFit[x],{x,0,Pi}]

Show[wDataPlot,aUwFitPlot]

aFit=LinearModelFit[xw,{LegendreP[2,Cos[θ]],LegendreP[4,Cos[θ]]},{θ},Weights->1/σ^2,VarianceEstimatorFunction->(1&)]

Comparing weighted and unweighted parameter fits

aFit["ParameterTable"]

aUnweightedFit["ParameterTable"]

Show[wDataPlot,Plot[{aUnweightedFit[x],aFit[x]},{x,0,Pi},PlotStyle->{Blue,Red}]]

Mandatory tests - ALWAYS look at these graphics and numbers when using linear models

residuals=Table[ {xw[[i,1]],aFit["StandardizedResiduals"][[i]] },{i,7}]

ListPlot[residuals,AxesLabel->{"θ (rd)","normalized residual"}]

residualsW=Table[ {xw[[i,2]],aFit["StandardizedResiduals"][[i]] },{i,7}]

ListPlot[residualsW,AxesLabel->{"w exp","normalized residual"}]

chiSquare=Total[ (aFit["FitResiduals"]/σ)^2]

NonlinearModelFit

an example with a simple sinus function

data={{0.00,-0.8,0.5},{0.25,9.5,0.8},{0.5,-7.3,0.7},{0.75,-2.3,0.5},{1.00,11.0,0.9},{1.25,-5.5,0.6},{1.5,-5.7,0.6},{1.75,10.4,0.9},{2.00,-2.3,0.5}}

fit=NonlinearModelFit[data[[All,{1,2}]],{a Sin[w t]},{{a,10},{w,8}},{t},Weights->1/data[[All,3]]^2,VarianceEstimatorFunction->(1&)]

fit["ParameterTable"]

χ2=Total[(fit["FitResiduals"]/data[[All,3]])^2]

pχ2=100(1-CDF[ChiSquareDistribution[Length[data]-2],χ2])

ListPlot[Transpose[{ data[[All,1]],fit["FitResiduals"]}]]

ListPlot[Transpose[{ data[[All,2]],fit["FitResiduals"]}]]

Needs["ErrorBarPlots`"]

Show[ErrorListPlot[data,PlotRange->{-12,12}],Plot[fit[x],{x,0,2}]]

Exercise

Ajuste os parâmetros do polinômio y=a+b x + c (x^3) ao conjunto de dados z= {x,y} abaixo. Os desvios-padr~eos são todos iguais a 0.5. Calcule (χ^2) e faça os gráficos necessários à avaliação da qualidade do ajuste.

z={{-3.0,8.7},{-2.5,5.6},{-2.0,4.6},{-1.5,4.4},{-1.0,3.3},{-0.5,2.8},{0,1.7},{0.5,2.8},{1.0,1.8},{1.5,0.9},{2.0,0.8},{2.5,-0.4},{3.0,-2.7},{3.5,-5.3},{4.0,-6.4}}