# NonLinearFit with data

i've data looking like this:

ListPlot[data]


Now I want to make a NonLinearFit

fit = NonlinearModelFit[data, a*Sin[b*t], {a, b}, t]
Plot[fit[t], {t, 0, 20}]


But the Plot looks like this:

Whats the reason why there is a wrong Plot?

• Try initial values for the constants. Nov 23, 2016 at 21:17
• how do i do this? Nov 23, 2016 at 21:21
• @dnrhead Look up the documentation for NonlinearModelFit; the fourth bullet in "Details and Options" shows how to specify a starting value for the parameters. Nov 23, 2016 at 21:39
• Thank you, now it's working. Thank you. Nov 23, 2016 at 21:43

## 1 Answer

This is a case that you gotta have good starting values. A contour plot of the root mean square (the function that is essentially minimized) shows how the algorithm can get into trouble with bad starting values.)

(* Generate some data *)
data = Table[{x/10., 0.8 Sin[0.645 x/10]}, {x, 0, 200}];

(* Default starting values of 1 *)
badfit = NonlinearModelFit[data, a Sin[b t], {a, b}, t]

(* Better starting values *)
goodfit = NonlinearModelFit[data, a Sin[b t], {{a, .6}, {b, 0.6}}, t]

(* Function that determines the root mean square error *)
n = Length[data];
rmse[aa_, bb_] := Sqrt[Total[(data[[All, 2]] - aa Sin[bb data[[All, 1]]])^2/(n - 2)]]

(* Show contour plot for values of a and b and estimates *)
Show[ContourPlot[rmse[a, b], {a, 0, 1.5}, {b, 0.1, 1.5},
FrameLabel -> (Style[#, Bold, Large] & ) /@ {"a", "b"}],
ListPlot[{{a, b}} /. badfit["BestFitParameters"], PlotStyle -> {Red, PointSize[0.02]}],
ListPlot[{{a, b}} /. goodfit["BestFitParameters"], PlotStyle -> {Green, PointSize[0.02]}]]


The red dot is the result of the default starting values and the green is with better starting values.

One can see that the algorithm might not travel towards the solution because of the nature of the contour plot if one starts too far away.

• Yes, very interesting. Good to know. Nov 23, 2016 at 21:53
• @ChrisDegnen And it's certainly not restricted to Mathematica. R, SAS, Minitab, you name it have similar issues. It's real hard (if not impossible) to write a completely robust optimization routine.
– JimB
Nov 23, 2016 at 21:57
• @JimBaldwin wonderful avoiding the 'badlands' for 'hic sunt dracones' :) Dec 10, 2016 at 2:17