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 on an interval . Split the interval into equal pieces of width
In each piece pick a sample point , build a rectangle of height and width , and add them up:
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 on with , so :
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.625The true area, as the next lesson shows, is . The midpoint sum is already within 0.05.
The for loop of integration
A Riemann sum is literally a loop with an accumulator:
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 (four times the rectangles, a quarter of the error). The midpoint error shrinks like (sixteen times smaller). That difference in order of accuracy matters a lot in Numerical Integration.
Seeing the rectangles
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 , and that limit is the definite integral:
The is a stretched S for "sum", and is what becomes. See The Definite Integral and the Fundamental Theorem.
Note: Where is negative, is negative. A Riemann sum measures signed area: parts below the axis count as minus.
In software
- Game loops and simulations add every frame: , . 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 .
- Probability and ML: a histogram with bar heights given as density sums to about 1 because 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 on with .
Answer
22
Solution
Exercise 2: Midpoint sum by hand
Midpoint sum of on with .
Answer
(the exact value is )
Solution
Exercise 3: Distance from a speed log
A drone logs its speed every 2 s: [0, 3, 5, 6, 6, 4] m/s at . Estimate the distance flown from to with left and right sums.
Answer
Left: 40 m, right: 48 m.
Solution
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 (exact ), find the smallest that gives an error below .
Answer
(error )
Solution
Increase until the error drops below the target.
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?
- It is larger
- It is equal
- It is smaller
- It depends on only
If you quadruple n, roughly how much smaller does the midpoint-sum error get for a smooth function?
- 4 times
- 16 times
- 2 times
- It does not change
What does a Riemann sum count for parts of the graph below the x-axis?
- Nothing
- Positive area
- Negative area
- Twice the area