Skip to main content

9  Fitting Models to Lab Data

Most lab reports come down to one move: you have a formula with an unknown constant in it, you have measurements, and you want the value of the constant that makes the two agree, along with its uncertainty. That is a fit. R does straight-line fits with lm() and curved ones with nls(), and both come with base R. The broom package turns their results into tibbles.

library(tidyverse)
library(broom)

9.1 A straight line with lm()

Chapter 8 ended with a straight line: \(T^2 = (4\pi^2/g)\,L\), so \(T^2\) against \(L\) has slope \(4\pi^2/g\). Measure the slope and you have measured \(g\).

Build pendulum_summary as in Chapter 7, this time with one mean period per length and a column for \(T^2\):

pendulum <- read_csv("data/pendulum.csv", show_col_types = FALSE)

pendulum_summary <- pendulum |>
  mutate(period_s = time_10_s / 10) |>
  summarise(period_s = mean(period_s), .by = length_m) |>
  mutate(period_sq_s2 = period_s^2)

pendulum_summary
#> # A tibble: 9 × 3
#>   length_m period_s period_sq_s2
#>      <dbl>    <dbl>        <dbl>
#> 1      0.2    0.897        0.805
#> 2      0.3    1.10         1.21 
#> 3      0.4    1.27         1.61 
#> 4      0.5    1.42         2.01 
#> 5      0.6    1.55         2.41 
#> 6      0.7    1.68         2.82 
#> 7      0.8    1.79         3.22 
#> 8      0.9    1.90         3.60 
#> 9      1      2.00         4.02

Now the fit. lm() stands for linear model, and its first argument is a formula: y ~ x, read as “y modelled by x”. The names are columns of the data frame you pass as data.

fit <- lm(period_sq_s2 ~ length_m, data = pendulum_summary)
summary(fit)
#> 
#> Call:
#> lm(formula = period_sq_s2 ~ length_m, data = pendulum_summary)
#> 
#> Residuals:
#>       Min        1Q    Median        3Q       Max 
#> -0.010260 -0.001765  0.002209  0.002732  0.005612 
#> 
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)    
#> (Intercept) 0.004623   0.004200   1.101    0.307    
#> length_m    4.011746   0.006429 623.979   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 0.00498 on 7 degrees of freedom
#> Multiple R-squared:      1,  Adjusted R-squared:      1 
#> F-statistic: 3.894e+05 on 1 and 7 DF,  p-value: < 2.2e-16

summary() prints more than you need. The part to read is the coefficient table. It has one row per fitted parameter: (Intercept) is where the line crosses the vertical axis, and the row named length_m is the slope, the coefficient that multiplies length_m. Estimate is the best-fit value and Std. Error is its standard uncertainty. So the slope is 4.012 ± 0.006 s²/m. The intercept is 0.005 ± 0.004 s², about one standard error away from zero, which is what the theory asks for. The last two columns test whether each coefficient differs from zero, a question you rarely need to ask about a slope.

You can also do the arithmetic inside the formula: lm(period_s^2 ~ length_m, ...) gives the same fit without the extra column.

Two helper functions pull out the pieces. coef() returns the estimates as a named vector, and confint() returns 95% confidence intervals:

coef(fit)
#> (Intercept)    length_m 
#> 0.004623098 4.011746278
confint(fit)
#>                    2.5 %     97.5 %
#> (Intercept) -0.005307373 0.01455357
#> length_m     3.996543411 4.02694914

By default lm() fits an intercept. To force the line through the origin, write period_sq_s2 ~ 0 + length_m. Do that only when you are sure the physics and the apparatus both give zero at zero. A free intercept is a useful check: if every length was measured to the top of the bob instead of its center, the intercept is where that mistake would show up.

9.2 From slope to g

The broom function tidy() returns the coefficient table as a tibble, which is easier to compute with than printed text.

fit_table <- tidy(fit)
fit_table
#> # A tibble: 2 × 5
#>   term        estimate std.error statistic  p.value
#>   <chr>          <dbl>     <dbl>     <dbl>    <dbl>
#> 1 (Intercept)  0.00462   0.00420      1.10 3.07e- 1
#> 2 length_m     4.01      0.00643    624.   7.17e-18

The slope is in row 2. Since \(g = 4\pi^2/\text{slope}\), and \(g\) depends on the slope alone, the relative uncertainty of \(g\) equals the relative uncertainty of the slope.

slope    <- fit_table$estimate[2]
slope_se <- fit_table$std.error[2]

g    <- 4 * pi^2 / slope
g_se <- g * slope_se / slope

c(g = g, g_se = g_se)
#>          g       g_se 
#> 9.84070648 0.01577089

Round the uncertainty to one significant figure, then round the value to the same decimal place: \(g = 9.84 \pm 0.02\) m/s². The accepted value, 9.81 m/s², sits just under two standard uncertainties below that, and inside the 95% interval you get by putting the confint() limits through the same formula (9.80 to 9.88 m/s²). The sentence for the lab report is “consistent with the accepted value at the two-sigma level”, and never “the fit proves \(g\) is 9.84”.

Chapter 7 got 9.82 ± 0.01 m/s² from the same data by averaging nine separate estimates, which quietly assumes the line passes through the origin. A fit forced through the origin gives the same 9.82 ± 0.01. The free intercept costs some precision and buys the check on the apparatus, and the two answers agree within the larger uncertainty.

TipPropagating uncertainty in general

When a result depends on several independent measurements, add the contributions in quadrature. For a single measurement \(g = 4\pi^2 L/T^2\), the relative uncertainties combine as \(\sqrt{(\sigma_L/L)^2 + (2\sigma_T/T)^2}\), the 2 coming from the power of \(T\):

rel_length <- 0.002 / 0.500  # length 0.500 m, known to 2 mm
rel_period <- 0.01 / 1.42    # period 1.42 s, known to 0.01 s
sqrt(rel_length^2 + (2 * rel_period)^2)
#> [1] 0.01464149

About 1.5%, nearly all of it from the stopwatch. One measurement gives \(g\) to 1.5%; the nine-point fit above gives it to 0.16%.

9.3 Checking the fit with broom

broom has two more functions. glance() gives one row of whole-fit statistics:

glance(fit) |>
  select(r.squared, sigma, nobs)
#> # A tibble: 1 × 3
#>   r.squared   sigma  nobs
#>       <dbl>   <dbl> <int>
#> 1     1.000 0.00498     9

sigma is the typical vertical distance of a point from the line, here 0.005 s². r.squared rounds to 1, and you should not be impressed: gently curved data routinely scores above 0.99.

The better check is the residuals, the measured values minus the fitted ones. augment() returns the original data with .fitted and .resid columns added, ready for ggplot2. One new geom, geom_hline(), draws a horizontal reference line at zero:

augment(fit) |>
  ggplot(aes(x = length_m, y = .resid)) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_point() +
  labs(x = "Length (m)", y = "Residual in T² (s²)")

Residuals of the pendulum fit against length. Nine points scattered above and below zero with no trend; the point at 0.9 m is lowest, at about -0.010.

Look for two things. First, pattern: residuals that curve like a smile or a frown, or that fan out as \(L\) grows, mean the model is missing something, whatever \(R^2\) says. Second, outliers. Here the points scatter on both sides of zero with no trend, which is what a good fit looks like. The point at 0.9 m sits lowest, about 0.010 s² under the line, twice the typical scatter. It is the first trial you would repeat.

9.4 A curve with nls()

Not every law can be turned into a straight line. Newton’s law of cooling, from Chapter 8, says a hot object approaches room temperature exponentially:

\[T(t) = T_\text{room} + \Delta T \, e^{-t/\tau} ,\]

with three unknowns: the room temperature, the initial excess \(\Delta T\), and the time constant \(\tau\). The log plot in Chapter 8 straightened it only by assuming a room temperature of 21.5 °C. Fit the curve directly instead.

cooling <- read_csv("data/cooling.csv", show_col_types = FALSE)
cooling
#> # A tibble: 16 × 2
#>    time_s temp_c
#>     <dbl>  <dbl>
#>  1      0   84.8
#>  2    120   73.1
#>  3    240   64.2
#>  4    360   56  
#>  5    480   50.2
#>  6    600   44.4
#>  7    720   40.2
#>  8    840   37.4
#>  9    960   34.2
#> 10   1080   31.9
#> 11   1200   30  
#> 12   1320   27.9
#> 13   1440   27.1
#> 14   1560   26  
#> 15   1680   25  
#> 16   1800   25.1

nls(), for nonlinear least squares, takes a formula with the whole model written out. The names in it that are not columns of the data, here t_room, delta, and tau, are the parameters to be fitted. Unlike lm(), it searches for the answer from a starting guess, so you must supply one for each parameter in start. A poor guess can stop it with an error such as singular gradient.

Read the guesses off the data. The temperature is levelling out in the mid twenties and still falling slowly, so try 20 °C for the room. The first reading is 84.8 °C, so the initial excess is about 65 °C. And \(\tau\) is the time for the excess to fall to \(1/e\) of its starting value, that is to \(20 + 65/e \approx 44\) °C, which the table shows at about 600 s.

cool_fit <- nls(
  temp_c ~ t_room + delta * exp(-time_s / tau),
  data  = cooling,
  start = list(t_room = 20, delta = 65, tau = 600)
)

tidy(cool_fit)
#> # A tibble: 3 × 5
#>   term   estimate std.error statistic  p.value
#>   <chr>     <dbl>     <dbl>     <dbl>    <dbl>
#> 1 t_room     21.4     0.264      81.0 5.78e-19
#> 2 delta      63.4     0.285     223.  1.14e-24
#> 3 tau       599.      7.79       77.0 1.12e-18

tidy() works on this fit exactly as it did on the straight line. The results: \(\tau = 599 \pm 8\) s, so the cup loses a factor of \(e\) of its excess temperature about every ten minutes, and \(T_\text{room} = 21.4 \pm 0.3\) °C, which agrees with the 21.5 °C assumed earlier. The fit found the room temperature without the water ever reaching it.

To draw the fitted curve, evaluate the model on a fine grid of times with predict(), then put the curve under the points with geom_line(). A geom given its own data argument draws from that table instead of the one in ggplot():

cool_curve <- tibble(time_s = seq(0, 1800, by = 10))
cool_curve <- cool_curve |>
  mutate(temp_c = predict(cool_fit, newdata = cool_curve))

ggplot(cooling, aes(x = time_s, y = temp_c)) +
  geom_line(data = cool_curve, color = "steelblue") +
  geom_point() +
  labs(x = "Time (s)", y = "Temperature (°C)")

Temperature against time for the cooling cup. Sixteen data points fall from 85 to 25 degrees Celsius, with a smooth fitted exponential curve passing through them.

augment(cool_fit) gives residuals here too.

9.5 Weighted fits

Everything above treats all points as equally trustworthy. When each point has its own known uncertainty, stored in a column called, say, sigma, pass weights = 1 / sigma^2 to lm() or nls() and the precise points will count for more.

That is the fitting toolkit a first lab course needs: a formula, lm() or nls(), tidy() for the numbers, and a residual plot before you believe any of them. The next part of the book goes the other way. Instead of extracting a constant from measured motion, Chapter 10 starts from the constants and computes the motion.