5.3b Integration labs
Source: Lab ideas from Computational Physics (Landau, Páez, Bordeianu), §5.3–§5.3.5. Rewritten as original drills. Continues 5.3 Integration algorithms.
Build the skeleton: Riemann boxes, trapezoid / Simpson, Romberg, and a weight-sum audit. Stubs fail until filled in.
Formula refresh
Warm up: pick the matching equation among lookalikes (same walk as the theory lesson).
Labs
Approximate with equal boxes using left endpoints:
, sum .
For on , print the approximation with 10 decimals.
Input: N.
Write-ups
Using “sum”, “weights”, and “nodes”, explain:
In one sentence: what do all numerical integration algorithms share?
Minimum 3 words. Your answer must include: “sum”, “weights”, “nodes”.
Meet the writing requirements, then you can open the model answer.
Explorers
# quad_ref.py
import math
def left_sum(f, a, b, N):
h = (b - a) / N
return h * sum(f(a + i * h) for i in range(N))
def mid_sum(f, a, b, N):
h = (b - a) / N
return h * sum(f(a + (i + 0.5) * h) for i in range(N))
def trap(f, a, b, N):
h = (b - a) / N
s = 0.5 * (f(a) + f(b))
for i in range(1, N):
s += f(a + i * h)
return s * h
def simpson(f, a, b, N):
h = (b - a) / N
s = f(a) + f(b)
for i in range(1, N, 2):
s += 4 * f(a + i * h)
for i in range(2, N, 2):
s += 2 * f(a + i * h)
return s * h / 3
def romberg(f, a, b, N):
return (4 * trap(f, a, b, 2 * N) - trap(f, a, b, N)) / 3
Next: 5.4 Gaussian quadrature.