Line Fitting

Let

\begin{displaymath}
y = mx +q + \varepsilon
\end{displaymath} (4.99)

be the explicit equation of the line, with all measurement error assumed to lie along the $y$ axis. With error along the $y$ axis, the cost function to be minimized is
\begin{displaymath}
S = \frac{1}{2n} \sum_{i=1}^{n} { \left( m x_i + q - y_i \right)^2 }
\end{displaymath} (4.100)

The solution is the point at which the gradient of $S$ with respect to $m$ and $q$ is zero:

\begin{displaymath}
\begin{array}{rl}
\frac{\partial S}{\partial m} & = \frac{...
...\sum y_i \right) = m \bar{x} + q - \bar{y} = 0 \\
\end{array}\end{displaymath} (4.101)

that is:
\begin{displaymath}
\begin{array}{l}
m = \dfrac{ \bar{(xy)}-\bar{x}\bar{y}}{\b...
...{\text{var}(x)} \\
q = - m \bar{x} + \bar{y} \\
\end{array}\end{displaymath} (4.102)

where $\bar{x}$ is the mean of the samples $x_i$ (the same notation is used for the other quantities). The line passes through the point $(\bar{x},\bar{y})$, the centroid of the distribution.

This result can easily be adapted to minimize the deviation along the $x$ rather than the $y$, or to represent the line equation in implicit form.



Paolo medici
2026-10-19