# NonlinearModelFit gives weird result

I was trying to fit some data similar to sine, but always get weird results. So I searched and found this post.

Surprisingly, I can not reproduce the result. With below code

plot = DateListPlot[
WeatherData["Toronto",
"MeanTemperature", {{2016, 1, 1}, {2019, 12, 31}, "Day"},
Joined -> True]];
data = Cases[plot, Line[{x__}] -> x, Infinity];
mod = NonlinearModelFit[data, a*Sin[b*x + c] + d, {a, b, c, d}, x,
Method -> "NMinimize"];
Show[ListPlot[data],
Plot[mod[x], {x, Min[data[[All, 1]]], Max[data[[All, 1]]]}]]


What I got is

My Mathematica version is 12.2.0.0. What is wrong?

• Look at the x-scale in the original post and your x-scale. NonlinearModelFit needs some reasonable starting values for the parameters, otherwise it sets them to 1. Instead of {a, b, c, d} write {a, {b, 10^-11}, c, d}. Sep 17 at 8:35
• @Domen Thank you for reply. But I got "NMinimize::parchange: Inappropriate parameter: InitialPoints -> {1,1/100000000000,1,1}, changed to Automatic." Sep 17 at 8:37
• In this case drop the Method -> "NMinimize" option and use reasonable guesses for the parameters. a: (Quantile[data[[All, 2]], 0.95] - Quantile[data[[All, 2]], 0.05])/2. b: (2 \[Pi] 4)/Differences[MinMax[data[[All, 1]]]]. d: Mean[data[[All, 2]]]. Or {{a, 16}, {b, 2 10^-7}, c, {d, 10}}. Because a, c, and d are on wildly different scales than b, you'll just have to guess well to get convergence.
– JimB
Sep 17 at 9:13
• If one knew enough to roughly equalize the values of the parameters with a*Sin[10^(-7) b*x + c] + d, then using no initial values and Method -> "NMinimize" would work.
– JimB
Sep 17 at 9:18
• One more comment: this issue doesn't just pertain to Mathematica regression functions. The same thing happens with R, SAS, etc. Especially if the proposed model is based on theoretical considerations, then one should attempt to figure out reasonable starting values and modify the appearance of the model to have parameters of similar orders of magnitude to assist with the stability of the iterative procedures.
– JimB
Sep 17 at 16:41