2
$\begingroup$

This question already has an answer here:

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]

Plot of data

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.

$\endgroup$

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ NonlinearModelFit tries negative y. Try adding y>0 as a constraint. You might also use Abs[y] in the expression. $\endgroup$ – george2079 Nov 18 '15 at 17:42
  • $\begingroup$ ( actually you need y>=3 ) $\endgroup$ – george2079 Nov 18 '15 at 17:45
  • $\begingroup$ @george2079: F >= 3, surely? $\endgroup$ – Michael Seifert Nov 18 '15 at 17:59
  • $\begingroup$ 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) $\endgroup$ – george2079 Nov 18 '15 at 18:03
  • $\begingroup$ Not really sure how to implement these constraints. $\endgroup$ – Tyediedhair Nov 18 '15 at 20:15
4
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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.} *)
$\endgroup$

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