2

The only difference between my code1 and code2 is the coefficient of Sin is 84.95 in the 1st case and 84.96 in the 2nd, I really wonder why such a small variation makes such a large difference in results.

code1 works perfectly, but code2 produces a fit to the data that is way off from the function used to generate the data.

code1

Clear[nlm, data]
data = Table[{i, 84.96 Sin[2 i] + 50}, {i, 1, 20}];
nlm = NonlinearModelFit[data, a Sin[b x + c] + d, {a, b, c, d}, x]
Show[ListPlot[data], Plot[nlm[x], {x, 0, 20}], Frame -> True]

code2

Clear[nlm, data]
data = Table[{i, 84.95 Sin[2 i] + 50}, {i, 1, 20}];
nlm = NonlinearModelFit[data, a Sin[b x + c] + d, {a, b, c, d}, x]
Show[ListPlot[data], Plot[nlm[x], {x, 0, 20}], Frame -> True]

And it gets even worse at 83 and less. Am I misusing NonlinearModelFit?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257

1 Answers1

4

The starting values (which by default are all 1.0) need to be closer to the final values:

Clear[nlm, data]
data = Table[{i, 84.95 Sin[ 2 i] + 50}, {i, 1, 20}];
nlm = NonlinearModelFit[data, a Sin[b x + c] + d, {{a, 40}, {b, 2}, {c, -1}, {d, 80}}, x]
nlm["BestFitParameters"]
(* {a -> 84.95, b -> 2., c -> 1.30312*10^-15, d -> 50.} *)

Alternatively, some (reasonable) restrictions on the parameters might help, too:

Clear[nlm, data]
data = Table[{i, 84.95 Sin[ 2 i] + 50}, {i, 1, 20}];
nlm = NonlinearModelFit[
  data, {a Sin[b x + c] + d, -π <= c <= π}, {a, {b, 2.1}, c, d}, x, MaxIterations -> 1000]
(* {a -> 84.95, b -> 2., c -> 3.39505*10^-18, d -> 50.} *)

Your particular equation seems particularly sensitive to starting values for b.

Update

Here is one display that attempts to show why there might be a narrow band of starting values that will get you the appropriate answer. I've plotted the standard error of estimate (square root of the residual error) against the fixed values of b ranging from 0 to 4.

standard error of estimate vs b

The algorithm is not likely to find the appropriate solution for b if the starting value is not near enough to 2.0. (I'll add a more directly related display in the next day or so.)

JimB
  • 41,653
  • 3
  • 48
  • 106