6.5.2b Cubic splines labs
Source: Lab ideas from Computational Physics (Landau, Páez, Bordeianu), §6.5.2–6.5.3. Rewritten as original drills. Continues 6.5.2 Cubic splines.
Build a natural cubic spline from scratch — no calling a library spline routine. Stubs fail until filled in.
Formula refresh
Warm up: pick the matching equation among lookalikes (same walk as the theory lesson).
Labs
Activity: Estimate g'' by forward difference
Implement the endpoint second-derivative estimate
Input: x1 g1 x2 g2 x3 g3. Print with 6 decimals.
Write-ups
Using “value”, “first”, “second”, and “derivative”, explain:
Which quantities does a cubic spline force to be continuous across interval boundaries?
Minimum 3 words. Your answer must include: “value”, “first”, “second”, “derivative”.
0 words
Meet the writing requirements, then you can open the model answer.
Explorers
# spline_ref.py — natural cubic spline: solve, evaluate, integrate (original sketch)
def natural_spline_M(xs, ys):
n = len(xs)
h = [xs[i + 1] - xs[i] for i in range(n - 1)]
A = [[0.0] * n for _ in range(n)]
b = [0.0] * n
A[0][0] = 1.0
A[n - 1][n - 1] = 1.0
for i in range(1, n - 1):
A[i][i - 1] = h[i - 1]
A[i][i] = 2.0 * (h[i - 1] + h[i])
A[i][i + 1] = h[i]
b[i] = 6.0 * ((ys[i + 1] - ys[i]) / h[i] - (ys[i] - ys[i - 1]) / h[i - 1])
for i in range(n):
piv = A[i][i]
for j in range(i + 1, n):
f = A[j][i] / piv
for k in range(n):
A[j][k] -= f * A[i][k]
b[j] -= f * b[i]
M = [0.0] * n
for i in range(n - 1, -1, -1):
s = b[i]
for k in range(i + 1, n):
s -= A[i][k] * M[k]
M[i] = s / A[i][i]
return M