Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

11. Fitting a straight line

School of Engineering, Nazarbayev University

Track: core  ·  Prerequisites: Chapters 1, 3 and 4

Reading: Taylor, ch. 8 · Bevington & Robinson, ch. 6 · Fornasini, ch. 10.3–10.4 · Rouaud, ch. II.C

Very often a quantity is obtained not from a single pair of measurements but from the slope or intercept of a graph: a spring constant from extension against load, a resistance from voltage against current, a rate constant from the logarithm of concentration against time. Fitting uses all the data at once, exposes points and trends that do not belong, and, done properly, returns the uncertainty of the slope and intercept.

In this notebook we

  1. derive the least-squares line and the uncertainties of its parameters;

  2. fit a data set and read the residuals;

  3. extend the method to points with different error bars and meet χ2\chi^2;

  4. verify the quoted uncertainties by simulation;

  5. list the pitfalls that the advanced notebook Chapter 13 treats in depth.

11.1 The principle of least squares

We have NN points (xi,yi)(x_i, y_i) and a model y=a+bxy = a + bx. We assume, for now, that

  • the xix_i are known much more precisely than the yiy_i;

  • every yiy_i has the same standard uncertainty σ\sigma;

  • the errors of different points are independent.

The vertical distance of a point from the line is the residual ri=yi−a−bxir_i = y_i - a - bx_i. The best line is taken to be the one that minimises the sum of squared residuals,

S(a,b)=∑i=1N(yi−a−bxi)2.S(a, b) = \sum_{i=1}^{N} (y_i - a - b x_i)^2 .

(For normally distributed errors this is also the line that makes the observed data most probable.) Setting the two partial derivatives to zero,

∂S∂a=−2∑i(yi−a−bxi)=0,∂S∂b=−2∑ixi(yi−a−bxi)=0.\frac{\partial S}{\partial a} = -2\sum_i (y_i - a - bx_i) = 0, \qquad \frac{\partial S}{\partial b} = -2\sum_i x_i (y_i - a - bx_i) = 0 .

The first equation gives a=yˉ−bxˉa = \bar y - b\bar x: the best line passes through the centroid (xˉ,yˉ)(\bar x, \bar y) of the data. Substituting into the second,

b=SxySxx,a=yˉ−b xˉ,b = \frac{S_{xy}}{S_{xx}}, \qquad a = \bar y - b\,\bar x,

with the abbreviations

Sxx=∑i(xi−xˉ)2,Sxy=∑i(xi−xˉ)(yi−yˉ).S_{xx} = \sum_i (x_i - \bar x)^2, \qquad S_{xy} = \sum_i (x_i - \bar x)(y_i - \bar y) .

11.2 Uncertainties of slope and intercept

The slope can be written as b=∑ikiyib = \sum_i k_i y_i with ki=(xi−xˉ)/Sxxk_i = (x_i - \bar x)/S_{xx} (the term with yˉ\bar y drops out because ∑i(xi−xˉ)=0\sum_i (x_i - \bar x) = 0). It is a linear function of the yiy_i, so the propagation law of Chapter 3 applies exactly:

ub2=∑iki2 σ2=σ2Sxx.u_b^2 = \sum_i k_i^2\,\sigma^2 = \frac{\sigma^2}{S_{xx}} .

In the same way a=∑i[1N−xˉ ki]yia = \sum_i \left[\tfrac1N - \bar x\,k_i\right] y_i, which gives

ua2=σ2(1N+xˉ2Sxx).u_a^2 = \sigma^2\left(\frac{1}{N} + \frac{\bar x^2}{S_{xx}}\right) .

Two practical lessons are contained in ub=σ/Sxxu_b = \sigma/\sqrt{S_{xx}}. The slope improves with more points, and it improves faster by spreading the points over a wide range of xx, since SxxS_{xx} grows with the square of the range.

If σ\sigma is not known in advance, it is estimated from the scatter of the points about the line,

s2=1N−2∑iri2.s^2 = \frac{1}{N-2}\sum_i r_i^2 .

The divisor is N−2N-2 because two parameters were fitted. (Two points define a line exactly and tell nothing about the scatter.)

11.3 Example: a spring

Known masses are hung from a spring and the position of a pointer is read from a scale. The load F=mgF = mg is known precisely; the position reading is good to about a millimetre. We therefore put the load on the horizontal axis and fit

x=x0+1k F.x = x_0 + \frac{1}{k}\,F .

The slope is the compliance 1/k1/k. The data below are simulated, with a true spring constant of 25.0 N/m, so that we can judge the outcome.

intercept = 0.0321935 +/- 0.00071
slope     = 0.0398545 +/- 0.00023
correlation(intercept, slope) = -0.886
residual standard deviation = 0.00104  (dof = 8)

The spring constant is k=1/bk = 1/b, and by the power rule its relative uncertainty equals that of the slope.

k   = 25.09 ± 0.15 N/m    (true value 25.0)
x0  = 32.19 ± 0.71 mm    (true value 32.0)
scatter about the line: s = 1.04 mm   (true sigma 1.0 mm)

Always plot the residuals

A fit returns numbers whether or not the model is appropriate. The plot that tells the two cases apart is the plot of residuals against xx. For a correct model they scatter randomly about zero with no pattern. The lower panels below show a spring that stiffens at large extension (a small quadratic term in the extension): the straight-line fit still looks acceptable in panel (c), but the residuals in panel (d) form an arch, a sure sign that the model is missing something.

stiffening spring: R^2 of the straight-line fit = 0.9980
<Figure size 1012x770 with 4 Axes>

The shaded band is the uncertainty of the fitted line itself. It is narrowest near the centroid of the data and widens towards the ends and beyond: extrapolation is always less certain than interpolation. The band is computed by fit.predict, which accounts for the fact that slope and intercept, having been determined from the same data, are not independent of each other. Why that matters is the subject of Chapter 13.

11.4 Points with different error bars: weighted fits and χ2\chi^2

If the points have different, known uncertainties σi\sigma_i, a precise point should pull the line harder than an imprecise one. As with the weighted mean (Section 4.6), each squared residual is divided by its variance, and we minimise

χ2(a,b)=∑i=1N(yi−a−bxi)2σi2.\chi^2(a, b) = \sum_{i=1}^{N} \frac{(y_i - a - bx_i)^2}{\sigma_i^2} .

The solution has the same form as before with every sum weighted by wi=1/σi2w_i = 1/\sigma_i^2. For instance, with xˉw=∑wixi/∑wi\bar x_w = \sum w_i x_i / \sum w_i,

b=∑iwi(xi−xˉw)(yi−yˉw)∑iwi(xi−xˉw)2,ub2=1∑iwi(xi−xˉw)2.b = \frac{\sum_i w_i (x_i - \bar x_w)(y_i - \bar y_w)}{\sum_i w_i (x_i - \bar x_w)^2}, \qquad u_b^2 = \frac{1}{\sum_i w_i (x_i - \bar x_w)^2} .

The minimum value of χ2\chi^2 is a measure of the goodness of fit. Each term is about one if the model is right and the error bars are right, and two parameters have been adjusted, so we expect

χmin2≈N−2≡ν,orχν2=χmin2/ν≈1,\chi^2_\text{min} \approx N - 2 \equiv \nu , \qquad\text{or}\qquad \chi^2_\nu = \chi^2_\text{min}/\nu \approx 1 ,

with a typical spread of 2/ν\sqrt{2/\nu} in χν2\chi^2_\nu.

ObservationLikely meaning
χν2≈1\chi^2_\nu \approx 1model and error bars are consistent with the data
χν2≫1\chi^2_\nu \gg 1wrong model, or error bars underestimated
χν2≪1\chi^2_\nu \ll 1error bars overestimated (or correlated)

Example: a rate of gas production measured at eight temperatures, with a detector whose noise grows with the signal.

weighted fit
intercept = 1.18684 +/- 0.082
slope     = 0.0843827 +/- 0.0024
correlation(intercept, slope) = -0.883
chi2 / dof = 6.65 / 6 = 1.11

unweighted fit of the same data
intercept = 1.31533 +/- 0.21
slope     = 0.0817578 +/- 0.0036
correlation(intercept, slope) = -0.923
residual standard deviation = 0.233  (dof = 6)

true values: intercept 1.2, slope 0.085

Both fits are consistent with the true values. The weighted fit has the smaller uncertainties, because it relies mostly on the precise points at low temperature, and its χν2\chi^2_\nu confirms that the scatter is of the size the error bars predict.

11.5 Checking the uncertainties by simulation

Is ubu_b really the standard deviation of the slope? As in Chapter 4 we can repeat the whole experiment on the computer. If the formula is right, the fitted slopes of many simulated spring experiments scatter with standard deviation ubu_b, and the interval b±ubb \pm u_b contains the true slope in about 68 % of them.

standard deviation of the fitted slopes : 2.231e-04 m/N
formula sigma / sqrt(Sxx)               : 2.245e-04 m/N
typical quoted u_b (from the scatter)   : 2.157e-04 m/N
fraction of fits with |b - b_true| < u_b: 0.662

The spread of the slopes matches the formula. The coverage, about 66 %, falls a little short of 68 % for the reason met in Section 4.4: with ten points the scatter ss is estimated from only eight degrees of freedom. Student’s tt with ν=N−2\nu = N - 2 repairs this exactly.

11.6 Pitfalls

  • Which variable goes on which axis. Ordinary least squares assumes the uncertainty is in yy only. Put the more precisely known variable on the horizontal axis. If both are uncertain, see Chapter 13.

  • Slope and intercept are correlated. They come from the same data. Any quantity computed from both (a predicted value, an xx-intercept) needs their covariance, not just uau_a and ubu_b.

  • Transforming the data changes the weights. Taking logarithms to turn an exponential into a straight line also transforms the error bars: uln⁡y=uy/yu_{\ln y} = u_y/y. Equal error bars in yy become very unequal ones in ln⁡y\ln y, and an unweighted fit of the transformed data is then wrong.

  • A high correlation coefficient proves little. The stiffening spring of Section 11.3 has R2>0.99R^2 > 0.99 (printed above the figure). Residuals and χ2\chi^2 are the tests of a model, not R2R^2.

  • Outliers. One bad point far from the centroid can turn the line. Do not delete points because they look wrong; find out why they are wrong, or keep them.

Summary

  • Least squares gives b=Sxy/Sxxb = S_{xy}/S_{xx} and a=yˉ−bxˉa = \bar y - b\bar x, with ub=σ/Sxxu_b = \sigma/\sqrt{S_{xx}} and ua=σ1/N+xˉ2/Sxxu_a = \sigma\sqrt{1/N + \bar x^2/S_{xx}}.

  • A wide range of xx is the most effective way to a precise slope.

  • With known, unequal error bars, weight each point by 1/σi21/\sigma_i^2 and check that χ2≈N−2\chi^2 \approx N - 2.

  • Plot the residuals. Always.

Exercises

  1. Refit the spring data using only the five smallest loads. By what factor does uku_k grow, and why is it much more than 2\sqrt 2?

  2. In Section 11.4, deliberately halve all error bars and refit. What happens to the parameter uncertainties and to χν2\chi^2_\nu? What would you conclude if you saw this in a real experiment?

  3. The voltage across a discharging capacitor is V=V0e−t/τV = V_0 e^{-t/\tau}. Simulate ten points with the same absolute noise on VV, and fit ln⁡V\ln V against tt (a) unweighted and (b) weighted with σln⁡V=σV/V\sigma_{\ln V} = \sigma_V/V. Repeat many times. Which estimate of τ\tau scatters less?

  4. Use fit.predict to find the pointer position expected for a load of 10 N and its uncertainty. Why should this number be treated with caution beyond its quoted uncertainty?