NonlinearModelFit gives imaginary numbers [duplicate]

I am having trouble using NonlinearModelFit to fit to data generated by the equation I am trying to fit to.

test = Table[{x, ((Sqrt[3] + Sqrt[x + 3])^2)^(2/3) -
Sqrt[3 ((Sqrt[3] + Sqrt[x + 3])^2)^(1/3)] -
((Sqrt[3] + Sqrt[3])^2)^(2/3) -
Sqrt[3 ((Sqrt[3] + Sqrt[3])^2)^(1/3)] + 5},
{x, -3, 5, .1}
]


Here is the data I generated with the equation.

 Blah = ListPlot[test]


This is what it looks like

nlm = NonlinearModelFit[
test, ((Sqrt[y] + Sqrt[F + y])^2)^(2/3) -
Sqrt[y ((Sqrt[y] + Sqrt[F + y])^2)^(1/
3)] - ((Sqrt[y] + Sqrt[y])^2)^(2/3) -
Sqrt[y ((Sqrt[y] + Sqrt[y])^2)^(1/3)], {y}, F]


My attempt to fit. The error says there are imaginary numbers yet there are none.

marked as duplicate by Oleksandr R., user9660, MarcoB, ilian, m_goldbergNov 19 '15 at 22:00

• NonlinearModelFit tries negative y. Try adding y>0 as a constraint. You might also use Abs[y] in the expression. – george2079 Nov 18 '15 at 17:42
• ( actually you need y>=3 ) – george2079 Nov 18 '15 at 17:45
• @george2079: F >= 3, surely? – Michael Seifert Nov 18 '15 at 17:59
• you need F+y>=0 where F has a min value of -3 from the data. ( his choice of variables is a bit confusing, y is the fit parameter F is the independent data value) – george2079 Nov 18 '15 at 18:03
• Not really sure how to implement these constraints. – Tyediedhair Nov 18 '15 at 20:15

Here it is with the constraint. I changed the symbols to a,x just for readability (There was nothing wrong with the y,F except that single Caps are good to avoid )

nlm = NonlinearModelFit[
test,
{((Sqrt[a] + Sqrt[x + a])^2)^(2/3) -
Sqrt[a ((Sqrt[a] + Sqrt[x + a])^2)^(1/3)] - ((Sqrt[a] +
Sqrt[a])^2)^(2/3) - Sqrt[a ((Sqrt[a] + Sqrt[a])^2)^(1/3)]
+5 , (* constraint *) a >= 3}, {a}, x];

nlm["BestFitParameters"]

{a -> 3.}


You were also missing the +5..btw.

The following trick sometimes work:

f[a_?NumericQ, x_?NumericQ] :=
Module[{s = ((Sqrt[a] + Sqrt[x + a])^2)^(2/3) -
Sqrt[a ((Sqrt[a] + Sqrt[x + a])^2)^(1/3)] - ((Sqrt[a] +
Sqrt[a])^2)^(2/3) - Sqrt[a ((Sqrt[a] + Sqrt[a])^2)^(1/3)] + 5},
10^3 Im@s + Re@s]

nlm = NonlinearModelFit[test, {f[a, x]}, {a}, x,
Method -> {"NMinimize", Method -> "SimulatedAnnealing"}]

nlm["BestFitParameters"]
(* {a -> 3.} *)