Computational Quiz: Numerical Integration

Computational Quiz — Numerical Integration

A definite integral \(\int_a^b f(x)\,dx\) can be approximated by splitting \([a, b]\) into \(n\) equal subintervals of width \(h = \dfrac{b-a}{n}\) and adding up the area of \(n\) simple shapes under the curve.

Left Riemann sum — a rectangle of height \(f\) at the left edge of each subinterval: \[ R_n = h \sum_{k=0}^{n-1} f(x_k), \qquad x_k = a + kh. \]

Trapezoidal rule — a trapezium on each subinterval instead, using the heights at both ends: \[ T_n = h\left(\frac{f(a)}{2} + \sum_{k=1}^{n-1} f(x_k) + \frac{f(b)}{2}\right). \]

Write two Python functions, riemann_left_sum(f, a, b, n) and trapezoidal_rule(f, a, b, n), each returning the corresponding approximation above for any function f, interval [a, b], and number of subintervals n.

Before you submit anything, test your own code against this known answer. For \(f(x) = x^2\) on \([0, 1]\) with \(n = 4\) (so \(h = 0.25\)), a correct implementation gives \[ R_4 = 0.21875, \qquad T_4 = 0.34375. \] If your functions don’t produce these two numbers for these inputs, they’re not ready yet — don’t submit. There’s a Marimo notebook — Computational Quiz practice, runs directly in your browser, also on the course homepage under Computational Quiz — with this exact check already wired up, so you don’t even need to type it yourself: write your functions in it, run it, and it tells you directly whether you match.

This is a CodeRunner quiz question on Moodle: paste your two function definitions into the answer box. Marks come entirely from the hidden tests — there’s no written component.