Skip to main content

6.6b Least-squares fitting labs

Source: Lab ideas from Computational Physics (Landau, Páez, Bordeianu), §6.6–6.7.2. Rewritten as original drills. Continues 6.6 Least-squares fitting.

Implement linear regression and chi-square from scratch — no numpy.polyfit or scipy.stats.linregress. Stubs fail until filled in.

Formula refresh​

Warm up: pick the matching equation among lookalikes (same walk as the theory lesson).

Labs​

Activity: Linear regression (equal weights)

Implement the numerically stable linear-regression formulas (6.51) with σi≡1\sigma_i\equiv1:

a2=SxySxx,a1=yˉ−a2xˉ,Sxy=∑i(xi−xˉ)(yi−yˉ),Sxx=∑i(xi−xˉ)2.a_2=\frac{S_{xy}}{S_{xx}},\quad a_1=\bar y-a_2\bar x,\quad S_{xy}=\sum_i(x_i-\bar x)(y_i-\bar y),\quad S_{xx}=\sum_i(x_i-\bar x)^2.

Input: first line n, then n lines of x_i y_i. Print a1 a2 with 6 decimals.

Write-ups​

0/4 solved
6.6b.W1

Using “weight”, “sigma”, and “error”, explain:

Why does chi-square divide each squared residual by sigma_i^2 instead of leaving it unweighted?

Minimum 3 words. Your answer must include: “weight”, “sigma”, “error”.

0 words/ 3 min

Meet the writing requirements, then you can open the model answer.

Explorers​

# lsq_ref.py — linear regression and 3x3 quadratic fit (original sketch)
def linreg(xs, ys):
n = len(xs)
xbar = sum(xs) / n
ybar = sum(ys) / n
sxy = sum((xs[i] - xbar) * (ys[i] - ybar) for i in range(n))
sxx = sum((xs[i] - xbar) ** 2 for i in range(n))
a2 = sxy / sxx
a1 = ybar - a2 * xbar
return a1, a2

Next: 6.8 Nonlinear fit to a resonance.