i've data looking like this:


Plot One

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?

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

1 Answer 1


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]}]]

Contour plot of root mean square error

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.

  • $\begingroup$ Yes, very interesting. Good to know. $\endgroup$ Nov 23, 2016 at 21:53
  • 1
    $\begingroup$ @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. $\endgroup$
    – JimB
    Nov 23, 2016 at 21:57
  • 1
    $\begingroup$ @JimBaldwin wonderful avoiding the 'badlands' for 'hic sunt dracones' :) $\endgroup$
    – ubpdqn
    Dec 10, 2016 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.