Numerical integration and differentiation
Turn sampled data into totals and rates: the trapezoid rule for distance from speed, finite differences for speed from position, and how step size and noise create error.
Lesson 4 of 6 · 35 min · Self-paced · Free
Why calculus on data?
A wheel encoder tells a robot how fast it is going, sample by sample — but you want to know how far it has travelled. A distance sensor tells you where an object is at each moment — but a collision warning needs to know how fast it is approaching. Going from a rate to a total is integration; going from a quantity to its rate of change is differentiation.
In a maths class these are done with formulas. On a robot you rarely have a formula — you have a list of numbers taken at regular times. This lesson shows how to integrate and differentiate samples, and, just as importantly, how wrong the answers can be.
If you have not met calculus yet, the two ideas you need are simple. The integral of speed over time is the area under the speed–time graph, which is the distance travelled. The derivative of position is the slope of the position–time graph, which is the speed.
The trapezoid rule
Between two samples, we do not know exactly what happened. The simplest reasonable assumption is that the speed changed in a straight line. The area under that line is a trapezoid: its width is the time step Δt and its average height is the average of the two speeds.
area of one slice = ½ × (v₁ + v₂) × ΔtAdd up all the slices and you have the distance. Here is a made-up log of a robot accelerating and then cruising, sampled every 0.5 s:
times = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0] # s
speeds = [0.0, 0.18, 0.31, 0.40, 0.42, 0.41, 0.40] # m/s
distance = 0.0
for i in range(1, len(times)):
dt = times[i] - times[i - 1]
distance += 0.5 * (speeds[i] + speeds[i - 1]) * dt
print(f"Distance travelled: {distance:.3f} m")Output:
Distance travelled: 0.960 mCheck the first slice by hand: ½ × (0 + 0.18) × 0.5 = 0.045 m. Computing dt from the timestamps, rather than assuming it is constant, means the code still works if a sample arrives late — which, on real hardware, happens.
How accurate is it?
To measure the error of a method, test it on a problem with a known answer. The area under sin(x) from 0 to π is exactly 2. Here the trapezoid rule is written for a function, using n equal slices:
import math
def trapezoid(f, a, b, n):
"""Integrate f from a to b using n equal trapezoids."""
h = (b - a) / n
total = 0.5 * (f(a) + f(b))
for i in range(1, n):
total += f(a + i * h)
return total * h
for n in [4, 8, 16, 32]:
estimate = trapezoid(math.sin, 0.0, math.pi, n)
print(f"n = {n:2d} estimate = {estimate:.6f} error = {2 - estimate:.6f}")Output:
n = 4 estimate = 1.896119 error = 0.103881
n = 8 estimate = 1.974232 error = 0.025768
n = 16 estimate = 1.993570 error = 0.006430
n = 32 estimate = 1.998393 error = 0.001607Each time the number of slices doubles, the error falls by a factor of about four. Halving the step h quarters the error, so the error is proportional to h²: the trapezoid rule is a second-order method. Knowing the order lets you predict how many samples you need for a given accuracy.
Finite differences
To estimate a derivative from samples, use the slope between nearby points. There are three common versions, with a small step h:
forward: f′(x) ≈ (f(x + h) − f(x)) / h
backward: f′(x) ≈ (f(x) − f(x − h)) / h
central: f′(x) ≈ (f(x + h) − f(x − h)) / (2h)The central difference looks equally far ahead and behind, so its errors largely cancel. Let us test on sin(x) at x = 1, where the exact derivative is cos(1) ≈ 0.5403:
import math
x = 1.0
exact = math.cos(x)
print(f"{'h':>8} {'forward error':>14} {'central error':>14}")
for h in [0.1, 0.01, 0.001]:
forward = (math.sin(x + h) - math.sin(x)) / h
central = (math.sin(x + h) - math.sin(x - h)) / (2 * h)
print(f"{h:>8} {abs(forward - exact):>14.2e} {abs(central - exact):>14.2e}")Output:
h forward error central error
0.1 4.29e-02 9.00e-04
0.01 4.22e-03 9.00e-06
0.001 4.21e-04 9.01e-08(4.29e-02 is scientific notation for 4.29 × 10⁻², or 0.0429.) Dividing h by 10 divides the forward error by 10 — first order — but divides the central error by 100 — second order. For the same samples, the central difference is far more accurate.
Too small a step
If smaller steps are better, why not use h = 10⁻¹³? Try it:
import math
x = 1.0
exact = math.cos(x)
for h in [1e-5, 1e-8, 1e-11, 1e-13]:
central = (math.sin(x + h) - math.sin(x - h)) / (2 * h)
print(f"h = {h:.0e} central error = {abs(central - exact):.1e}")Output:
h = 1e-05 central error = 1.1e-11
h = 1e-08 central error = 3.0e-09
h = 1e-11 central error = 1.2e-06
h = 1e-13 central error = 1.8e-04Beyond a point, the error grows. Floats carry only about 16 significant digits. When h is tiny, sin(x + h) and sin(x − h) are almost equal, and subtracting them cancels most of those digits, leaving mostly rounding error — which is then divided by the tiny 2h. There is a best step size: big enough to avoid rounding trouble, small enough to keep the approximation error low.
Noise: the real enemy of differentiation
With real sensors, rounding error is small compared with measurement noise. Suppose a robot moves at a steady 0.2 m/s and its position is measured every 10 ms, but each reading is off by half a millimetre, alternately high and low (made-up noise, chosen to make the effect easy to see):
dt = 0.01 # s
true_position = [0.2 * i * dt for i in range(6)] # m, steady 0.2 m/s
noise = [0.0005, -0.0005, 0.0005, -0.0005, 0.0005, -0.0005] # m
measured = [p + n for p, n in zip(true_position, noise)]
speeds = [(measured[i + 1] - measured[i]) / dt for i in range(5)]
print([round(v, 2) for v in speeds])Output:
[0.1, 0.3, 0.1, 0.3, 0.1]A position error of only 0.5 mm turned into a speed error of 0.1 m/s — half the true speed! The difference of two noisy readings is divided by a small Δt, which amplifies noise. Integration does the opposite: adding many samples tends to average noise out (although any constant bias accumulates, which is why a robot that integrates a slightly offset accelerometer drifts further and further off).
Practical remedies for differentiating noisy data:
- Smooth the data first, for example with a moving average, accepting some delay.
- Take the difference over a longer interval (larger Δt), trading responsiveness for less noise.
- Measure the rate directly if possible: an encoder's tick rate, or a gyroscope instead of differentiating angles.
Recap
- Integration accumulates (area under the curve); differentiation measures change (slope).
- The trapezoid rule adds ½(v₁ + v₂)Δt slices; its error falls with h².
- Forward differences have error proportional to h; central differences, h².
- Steps that are too small cause rounding errors; there is a best step size.
- Differentiation amplifies noise, integration averages noise but accumulates bias.
- Always test a numerical method on a problem with a known answer.
Knowledge check
Check your understanding
Project
Programming project: from speed to distance and back
Create a made-up speed log for a robot that speeds up, cruises and slows down, with samples every 0.1 s for 10 s. Use a formula, so you also know the exact distance (for example, constant acceleration phases, where the distance can be worked out by hand from areas of triangles and rectangles).
- Integrate the speed log with the trapezoid rule and compare with your exact distance. Repeat using every second, fifth and tenth sample only. How does the error change?
- Integrate to get position at every sample, then differentiate the positions with forward and central differences. Compare with the original speeds.
- Add made-up noise to the positions using
random.uniform(-0.001, 0.001)(callrandom.seed(1)first so your results repeat). Differentiate again, then try smoothing the positions with a 5-sample moving average first. - Summarise what you learned about integrating and differentiating real data in a short paragraph.
No hardware is required.
Deliverables
- A Python 3 program with trapezoid integration and two finite-difference methods
- A table of distance errors for different sampling intervals
- Printed or plotted speeds recovered from noisy and smoothed positions, with a short discussion
Go further
- Trapezoidal rule — Wikipedia ↗
Derivation, error analysis and the uniform-grid formula used in this lesson.
- Finite difference — Wikipedia ↗
Forward, backward and central differences and their relationship to derivatives.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.