Skip to main content

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 ∑fiwi\sum f_i w_i 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​

Activity: Left Riemann sum

Approximate ∫abf(x) dx\int_a^b f(x)\,dx with NN equal boxes using left endpoints:

h=(b−a)/Nh=(b-a)/N, sum =h∑i=0N−1f(a+ih)= h\sum_{i=0}^{N-1} f(a+ih).

For f(x)=e−xf(x)=e^{-x} on [0,1][0,1], print the approximation with 10 decimals.

Input: N.

Write-ups​

0/5 solved
5.3b.W1

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”.

0 words/ 3 min

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

Explorers​

Figure 5.2 — equal-width Riemann boxes.

# 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.