TExcelTAD
Home › Calculus Essentials › Riemann Sums

Riemann Sums

A Riemann sum approximates the area under a curve by cutting it into thin rectangles and adding their areas. It is the bridge between a for loop that accumulates values and the exact integral of calculus.

Rectangles under a curve

Take a function ff on an interval [a,b][a, b]. Split the interval into nn equal pieces of width

Δx=b−an\Delta x = \frac{b - a}{n}

In each piece pick a sample point xi∗x_i^*, build a rectangle of height f(xi∗)f(x_i^*) and width Δx\Delta x, and add them up:

Sn=∑i=1nf(xi∗)⋅ΔxS_n = \sum_{i=1}^{n} f(x_i^*) \cdot \Delta x

Where you sample gives the common variants:

Rule Sample point in each piece Typical behaviour
Left sum left end underestimates an increasing function
Right sum right end overestimates an increasing function
Midpoint sum centre usually much closer than either

A worked example by hand

Area under f(x)=x2f(x) = x^2 on [0,2][0, 2] with n=4n = 4, so Δx=0.5\Delta x = 0.5:

text
left points    0, 0.5, 1, 1.5      heights 0, 0.25, 1, 2.25       sum 3.5   × 0.5 = 1.75
right points   0.5, 1, 1.5, 2      heights 0.25, 1, 2.25, 4       sum 7.5   × 0.5 = 3.75
mid points     0.25, 0.75, 1.25, 1.75  heights 0.0625, 0.5625, 1.5625, 3.0625  sum 5.25 × 0.5 = 2.625

The true area, as the next lesson shows, is 8/3≈2.66678/3 \approx 2.6667. The midpoint sum is already within 0.05.

The for loop of integration

A Riemann sum is literally a loop with an accumulator:

python · try it yourself
def riemann(f, a, b, n, rule="mid"):
    dx = (b - a) / n
    total = 0.0
    for i in range(n):
        left = a + i * dx
        if rule == "left":
            x = left
        elif rule == "right":
            x = left + dx
        else:
            x = left + dx / 2
        total += f(x) * dx
    return total

f = lambda x: x * x
for n in [4, 16, 64, 256, 1024]:
    L, R, M = (riemann(f, 0, 2, n, r) for r in ("left", "right", "mid"))
    print(f"n={n:5d}  left={L:.6f}  right={R:.6f}  mid={M:.6f}")
print("exact      ", 8 / 3)
n=    4  left=1.750000  right=3.750000  mid=2.625000
n=   16  left=2.421875  right=2.921875  mid=2.664062
n=   64  left=2.604492  right=2.729492  mid=2.666504
n=  256  left=2.651062  right=2.682312  mid=2.666656
n= 1024  left=2.662762  right=2.670574  mid=2.666666
exact       2.6666666666666665

Left and right errors shrink roughly in proportion to 1/n1/n (four times the rectangles, a quarter of the error). The midpoint error shrinks like 1/n21/n^2 (sixteen times smaller). That difference in order of accuracy matters a lot in Numerical Integration.

Seeing the rectangles

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

f = lambda x: x ** 2
a, b, n = 0, 2, 8
dx = (b - a) / n
mids = a + dx * (np.arange(n) + 0.5)

plt.figure(figsize=(6, 4))
xs = np.linspace(a, b, 200)
plt.plot(xs, f(xs), color="black", label="f(x) = x²")
plt.bar(mids, f(mids), width=dx, alpha=0.4, edgecolor="tab:blue", label="midpoint rectangles")
plt.legend()
plt.title(f"Midpoint sum, n = {n}: {np.sum(f(mids) * dx):.4f}")
print("midpoint sum:", round(float(np.sum(f(mids) * dx)), 4))
midpoint sum: 2.6562

The same sum with NumPy is one line, np.sum(f(mids) * dx): vectorised code replaces the explicit loop.

The limit

Make the rectangles thinner and thinner. For any continuous function, every choice of sample points gives the same limit as n→∞n \to \infty, and that limit is the definite integral:

∫abf(x) dx=lim⁡n→∞∑i=1nf(xi∗) Δx\int_a^b f(x)\,dx = \lim_{n \to \infty} \sum_{i=1}^{n} f(x_i^*)\,\Delta x

The ∫\int is a stretched S for "sum", and dxdx is what Δx\Delta x becomes. See The Definite Integral and the Fundamental Theorem.

Note: Where ff is negative, f(xi∗)⋅Δxf(x_i^*) \cdot \Delta x is negative. A Riemann sum measures signed area: parts below the axis count as minus.

In software

  • Game loops and simulations add rate×dt\text{rate} \times dt every frame: fuel used=∑burn rate×dt\text{fuel used} = \sum \text{burn rate} \times dt, distance=∑speed×dt\text{distance} = \sum \text{speed} \times dt. That is a left Riemann sum in time.
  • Metrics dashboards turn a sampled rate (requests per second, every 10 s) into a total by summing rate×10\text{rate} \times 10.
  • Probability and ML: a histogram with bar heights given as density sums to about 1 because ∑height×bin width\sum \text{height} \times \text{bin width} is a Riemann sum of the density.
  • Energy meters integrate power readings the same way.

Exercises

Exercise 1: Left sum by hand

Compute the left Riemann sum of f(x)=3x+1f(x) = 3x + 1 on [0,4][0, 4] with n=4n = 4.

Answer

22

Solution
Δx=1,left points 0,1,2,3heights 1,4,7,10,sum 22,× Δx=22(exact area: 28, the function is increasing so the left sum is too low)\begin{aligned} &\Delta x = 1, \quad \text{left points } 0, 1, 2, 3 \\ &\text{heights } 1, 4, 7, 10, \quad \text{sum } 22, \quad {\times}\,\Delta x = 22 \\ &\text{(exact area: 28, the function is increasing so the left sum is too low)} \end{aligned}

Exercise 2: Midpoint sum by hand

Midpoint sum of f(x)=1/xf(x) = 1/x on [1,3][1, 3] with n=2n = 2.

Answer

1/1.5+1/2.5=16/15≈1.06671/1.5 + 1/2.5 = 16/15 \approx 1.0667 (the exact value is ln⁡3≈1.0986\ln 3 \approx 1.0986)

Solution
Δx=1,midpoints 1.5 and 2.5sum=(11.5+12.5)⋅1=0.6667+0.4=1.0667\begin{aligned} &\Delta x = 1, \quad \text{midpoints } 1.5 \text{ and } 2.5 \\ &\text{sum} = \left(\frac{1}{1.5} + \frac{1}{2.5}\right) \cdot 1 = 0.6667 + 0.4 = 1.0667 \end{aligned}

Exercise 3: Distance from a speed log

A drone logs its speed every 2 s: [0, 3, 5, 6, 6, 4] m/s at t=0,2,…,10t = 0, 2, \ldots, 10. Estimate the distance flown from t=0t = 0 to t=10t = 10 with left and right sums.

Answer

Left: 40 m, right: 48 m.

Solution
python · try it yourself
v = [0, 3, 5, 6, 6, 4]
dt = 2
print("left :", sum(v[:-1]) * dt)
print("right:", sum(v[1:]) * dt)
left : 40
right: 48

Exercise 4: How many rectangles?

Using the midpoint rule on ∫01ex dx\int_0^1 e^x\,dx (exact e−1e - 1), find the smallest nn that gives an error below 10−610^{-6}.

Answer

n=268n = 268 (error ≈9.97×10−7\approx 9.97 \times 10^{-7})

Solution

Increase nn until the error drops below the target.

python · try it yourself
import math

def mid(f, a, b, n):
    dx = (b - a) / n
    return sum(f(a + (i + 0.5) * dx) for i in range(n)) * dx

exact = math.e - 1
n = 1
while abs(mid(math.exp, 0, 1, n) - exact) >= 1e-6:
    n += 1
print(n, abs(mid(math.exp, 0, 1, n) - exact))
268 9.968123064751921e-07

Test yourself

For an increasing function, how does the left Riemann sum compare with the true area?

  1. It is larger
  2. It is equal
  3. It is smaller
  4. It depends on nn only

If you quadruple n, roughly how much smaller does the midpoint-sum error get for a smooth function?

  1. 4 times
  2. 16 times
  3. 2 times
  4. It does not change

What does a Riemann sum count for parts of the graph below the x-axis?

  1. Nothing
  2. Positive area
  3. Negative area
  4. Twice the area