Here it is explained how to do a non linear model fit of data with measurement errors on y axis.

Is there a way to do a non linear fit of data including errors on the x axis? i.e. How to include errors on x axis data in NonLinearModelFit?

  • 1
    $\begingroup$ Nonlinear total least squares is a much harder problem than the ordinary version, and definitely not yet supported by NonlinearModelFit[]. $\endgroup$ Jan 25, 2017 at 21:14

1 Answer 1


So, like J.M pointed out in the comments there is no possible solution when you have BOTH x and y errors. BUT you can sometimes do something if you have x errors but negligible y errors. You just parameterize from $y(x)$ to $x(y)$ and fit it that way with your normal weights.

I made an example for you:

We make a fit for the function $y(x)=a\exp\left(b\cdot x\right)$

Lets make some random points:

function = a*Exp[b*x];
range = {{0, 1}, {0, 6}};
n = 30;
xErrors = RandomVariate[NormalDistribution[0, 0.1], n];
data = Table[{i/n + RandomReal[{-1, 1}]*xErrors[[i]], 
    function /. {x -> (i/n), a -> 2, b -> 1}}, {i, 1, n}];
(*create random data*)

Now we solve for $x(y)$

sol = (x /. 
    Refine[Solve[function == y, x, Reals], 
     a > 0 && y > 0]); (*solve the function for y*)


We reorder our data from $(x,y)$ to $(y,x)$ and do the weighted fits with instrumental-weights: $p_i=\delta_i^{-2}$

subData = Reverse /@ data; (*remap our data (x,y)\[Rule](y,x)*)
subFit = NonlinearModelFit[subData, Re@sol, {a, b}, y, 
  Weights -> 1/xErrors^2]; (*fit for x(y)*)

In the end we can plot this with and without weighted fits:

   {Evaluate@(NonlinearModelFit[data, function, {a, b}, x][
       "BestFit"]), (*fit unweighted with y(x)*)
    function /. 
     subFit["BestFitParameters"]}, (*use parameterized fit from x(y)*)
   {x, range[[1, 1]], range[[1, 2]]}, PlotStyle -> {Red, Blue}], 
  PlotRange -> range]
 , LineLegend[{Red, Blue}, {"unweighted", "weighted"}]]

which gives us the graph:

enter image description here

  • 2
    $\begingroup$ "no possible solution" - I didn't exactly say that. :D One could certainly write a routine for this kind of fitting, but it's complicated and delicate enough to implement that I'd prolly ask to get paid first. $\endgroup$ Jan 26, 2017 at 5:22
  • 2
    $\begingroup$ Just to attempt to add to what @J.M. has stated: it's much, much harder and complex than when the predictor variables are measured without error. And it's not just providing a different fitting algorithm. It involves what assumptions about the errors one can make (and not just willing to make). $\endgroup$
    – JimB
    Jan 26, 2017 at 16:24

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.