1
$\begingroup$

I've used the NonLinearModelFit function to get the fit for my data. I require the fit to to go through (0,0) (which I have succeeded in doing), however, I also need the fit to be positive, which I am yet to manage.

An example of my data:

mydata = {{0.700017, 0.2029}, {1.06981, 0.2028}, {1.17239, 0.4867},  {0.956762, 0.2104}, {1.48915, 0.45609}, {1.4274, 0.45039}, {1.4904, 0.5719}, {1.76748, 1.04605}, {1.57645, 1.06265}, , {1.866, 1.335}, {1.87094, 1.6095}, {1.96465, 1.8551}, {2.43712, 2.3769}, {2.63941, 3.771}, {2.76015, 4.133}}

This is how I fit the data currently:

modelquad = c x + a x^2;

QuadFit20 = NonlinearModelFit[mydata, {modelquad, (modelquad /. x -> 0) == 0}, {a, c}, x]

Which gives me a lovely fit, passing through (0,0), but does dip below y = 0. Is there any way of forcing the fit to be positive for all y values.

Any help would be greatly appreciated.

$\endgroup$
3
  • 1
    $\begingroup$ Please edit your question to include minimal example of data that demonstrates the problem that you are having. $\endgroup$
    – Bob Hanlon
    Mar 26, 2023 at 15:03
  • $\begingroup$ Sorry, example added! $\endgroup$
    – Schaef
    Mar 26, 2023 at 16:00
  • $\begingroup$ Why not use Max[0, c x + a x^2] for your model as you have only 1 data point where the prediction is less than 0 with the original model c x + a x^2. Also, just including an intercept will also fix the problem. If your original model without an intercept is a theoretical model, then that means you have data issues. $\endgroup$
    – JimB
    Mar 26, 2023 at 19:07

1 Answer 1

5
$\begingroup$
nlmf = NonlinearModelFit[mydata, {c x + a x^2, c >= 0}, {a, c}, x]

This constraint $c \ge 0$ comes from analyzing the derivative of the model: $df/dx = c + 2 a x$. If at (0,0) the model must remain non-negative, then this derivative must be non-negative as well. Thus, $c$ must be greater than or equal to 0.

There is no need to specify that the fit is 0 at $x=0$ as currently written, as that is required by the model's form.

Note also that as $c$ ends up being quite small, it is possible eliminate it from the model entirely and just fit $a x^2$ to the data. This can be done in LinearModelFit which provides a larger bank of statistics than NonlinearModelFit if those are of interest:

lmf = LinearModelFit[mydata, {x^2}, x, IncludeConstantBasis->False]
$\endgroup$
1
  • $\begingroup$ This does give positive values for $x>0$ but at the expense of a horrible fit. $\endgroup$
    – JimB
    Mar 26, 2023 at 19:21

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.