# NonLinearModelFit with errors on x axis?

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?

• Nonlinear total least squares is a much harder problem than the ordinary version, and definitely not yet supported by NonlinearModelFit[]. Jan 25 '17 at 21:14

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*)


$=\log(y/a)/b$

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:

Legended[Show[
ListPlot[data],
Plot[
{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: • "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. Jan 26 '17 at 5:22
• 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).
– JimB
Jan 26 '17 at 16:24