Least Squares Fitting—Exponential

Author

Eric W. Weisstein
August 6, 2002

This notebook downloaded from http://mathworld.wolfram.com/notebooks/Statistics/LeastSquaresFittingExponential.nb.

For more information, see Eric's MathWorld entry http://mathworld.wolfram.com/LeastSquaresFittingExponential.html.

©2005 Wolfram Research, Inc. except for portions noted otherwise

Notes

This is some of Eric's very old code.  It should be rewritten and cleaned up.

Code

ExponentialFit[x_List,y_List]:=Module[
		{n=Length[x],i,sxlny,slny,slnx,sx2,sx,b},
		sxlny=Sum[x[[i]]Log[y[[i]]],{i,n}];
		slny=Sum[Log[y[[i]]],{i,n}];
		sx2=Sum[x[[i]]^2,{i,n}];
		sx=Apply[Plus,x];
		{Exp[(slny sx2-sx sxlny)/(n sx2-sx^2)],(n sxlny-sx slny)/(n sx2-sx^2)}
]

ExponentialWeightedFit[x_List,y_List]:=Module[
		{n=Length[x],i,sxlny,sx2y,sxy,slny,sx2,sx,sy,sylny,sxylny,a,b},
		sxlny=Sum[x[[i]]Log[y[[i]]],{i,n}];
		sx2y=Sum[x[[i]]^2 y[[i]],{i,n}];
		sxy=x.y;
		slny=Sum[Log[y[[i]]],{i,n}];
		sx2=Sum[x[[i]]^2,{i,n}];
		sx=Apply[Plus,x];
		sy=Apply[Plus,y];
		sylny=Sum[y[[i]]Log[y[[i]]],{i,n}];
		sxylny=Sum[x[[i]]y[[i]]Log[y[[i]]],{i,n}];
		{a,b}={sx2y sylny-sxy sxylny,-sxy sylny+sy sxylny}/(sy sx2y-sxy^2);
		{Exp[a],b}
]

x=N[Table[i,{i,50}]];
y=Table[4.5Exp[.1 x[[i]]]+.1 Random[Real,{-60,60}],{i,50}];
{a1,b1}=ExponentialFit[x, y]

{a2,b2}=ExponentialWeightedFit[x,y]

yfit1=Table[a1 Exp[b1  i],{i,50}];
yfit2=Table[a2 Exp[b2  i],{i,50}];
Show[{ListPlot[y,DisplayFunction->Identity],
		ListPlot[yfit1,PlotJoined->True,DisplayFunction->Identity,PlotStyle->Dashing[{.011,.011}]],
		ListPlot[yfit2,PlotJoined->True,DisplayFunction->Identity,PlotStyle->Dashing[{.02,.02}]]},
  DisplayFunction->$DisplayFunction]