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
Implement the numerically stable linear-regression formulas (6.51) with :
Input: first line n, then n lines of x_i y_i. Print a1 a2 with 6 decimals.
Write-ups
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”.
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