Skip to the content of the web site.

Project Q.4: Differentiation and integration

We will look at four filters that approximate both the dirivative and the integral of the signal over the most recent time step.

Both integration and differentiation require us to understand how far apart the signals are given in time. You will first query the user for the time step. If the samples are being taken at 10 Hz or 0.1 s apart, the user would then enter:

What is the time step between readings? 0.1
Enter a file name: data.txt

Differentiation

When calculating the derivative, the simplest formula is rise over run, and in this case, the run is the time step:

$y[n] = \frac{x[n] - x[n - 1]}{\Delta t}$.

where $\Delta t$ is the time step. For example, if the time step is 0.1 and the input file is

0.0998
0.199
0.296
0.389
0.479
0.565
0.644
0.717
0.783
0.841

your output will be:

0.992
0.97
0.93
0.90
0.86
0.79
0.73
0.66
0.58

This approximates the derivative by calculating the rise over the run of the last two values, as shown in Figure 1.


Figure 1. Approximating the derivative.

A better approximation of the derivative is to use the formula

$y[n] = \frac{3x[n] - 4x[n - 1] + x[n - 2]}{2 \Delta t}$.

For the same intput file above, the output will be

0.959
0.91
0.885
0.84
0.755
0.7
0.625
0.54

This approximates the derivative by calculating the slope of an interpolating quadratic over the past three values, as shown in Figure 2.


Figure 2. Approximating the derivative using an interpolating quadratic.

Integration

If you are calculating an integral, the trapezoidal rule approximates the area as

$y[n] = \frac{x[n] + x[n - 1]}{2}\Delta t + y[n - 1]$.

where $\Delta t$ is the time step. For example, if the time step is 0.1 and the input file is

0.01494
0.03969
0.07394
0.11734
0.16954
0.22999
0.29804
0.37304
0.45424

This approximates the integral by calculating the area of the trapezoid as shown in Figure 3.


Figure 3. Approximating the integral using a trapezoid.

Using half of Simpson's rule, we have a better approximation with

$y[n] = \frac{5x[n] + 8x[n - 1] - x[n - 2]}{12}\Delta t + y[n - 1]$.

Now the output becomes

0.02476833333333333
0.05905166666666667
0.1024766666666667
0.15471
0.2152183333333333
0.2833183333333333
0.3583766666666667
0.4396433333333333

This approximates the integral by calculating the area under the quadratic interpolating the last three points, but only integrating this quadratic over the final interval, as shown in Figure 4.


Figure 4. Approximating the integral using an interpolating quadratic.