Signals and Systems
Noise, sinusoids, sampling, aliasing, quantisation, filters, Fourier series and the DFT
Eight chapters about the numbers that sensors produce and what you can honestly do with them. Describe a signal by amplitude, frequency and phase, sample it fast enough to avoid impostor frequencies, round it to a limited number of bits, smooth away noise at the cost of lag, then change the question: break any signal into sinusoids, measure them with the DFT and see what a filter does to each one.
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
1. Signals and noise
A signal is a quantity that changes in time: a voltage, a vibration, a temperature. The sinusoid is its simplest form, described completely by amplitude, frequency and phase, and its power is set by the RMS value rather than the peak. Real measurements arrive with noise from electronics, interference and the world itself. The signal-to-noise ratio says how much of what you see is the thing you wanted.
Figure 1.1. Amplitude, frequency and RMS (described in words)
Two cycles of a 2 V, 50 Hz sinusoid. The period is 20 ms, the angular frequency is 314.2 rad/s and a dashed line marks the RMS value of 1.414 V, the amplitude divided by √2.
Explanation
1.1 Signals: smooth waves and stored numbers
Your heartbeat, the hum of a fridge and a sensor wire all wiggle over time. How do engineers describe a wiggle with just a few numbers?
Continuous and discrete
An analog (continuous) signal has a value at every instant and can take any value: the voltage from a microphone, the height of a wave at sea. A digital (discrete) signal is a list of numbers: values at separate moments, each rounded to one of a fixed set of levels. Computers can only store the digital kind, so every sensor reading must be turned into numbers.
Amplitude, period, frequency
For a repeating signal: the amplitude is how far it swings from its middle (a wave from 0.45 V to 2.85 V has a middle of 1.65 V and an amplitude of 1.2 V). The period T is the time for one cycle. The frequency f is cycles per second, in hertz: f = 1 ÷ T. Resting heart rate: about 72 beats a minute = 1.2 Hz, period ≈ 0.83 s. The note A above middle C: 440 Hz, period ≈ 2.27 ms.
Why digital resists noise
Every wire picks up noise: small, random wiggles. In an analog signal the noise becomes part of the value and cannot be told apart. A digital wire only has to be read as 'high' or 'low', so a wiggle of 0.2 V on a 3.3 V logic signal changes nothing. Once a value is stored as a number it can be copied a million times without getting worse.
Common mix-ups
Digital signals are always better.
✓ The world is analog. Digital is a way to store and copy measurements reliably, but sampling and rounding lose detail if done badly.Amplitude is the distance from the bottom to the top of the wave.
✓ That is the peak-to-peak value. Amplitude is half of it, measured from the middle.
1.2 Where noise comes from
Run a sorting belt faster and the same colour sensor starts making mistakes. Nothing about the sensor changed. What did?
Physics makes noise
Thermal noise: electrons in every resistor jiggle with heat, so every voltage wobbles a little. Shot noise: light and current arrive as discrete particles, so a dim signal flickers. Quantisation: the converter rounds to its nearest step. These set a floor no software can go below.
The world adds more
Interference: motors, mains wiring and radios couple into sensor wires. Vibration: a shaking mount moves the sensor. Motion: a part passing a sensor is seen for a short time and at a slightly different spot every time. Good wiring, shielding and mounting reduce these at the source, which is always cheaper than filtering later.
Time buys quietness
Many sensors average internally over an exposure or integration time. Longer exposure means more averaging and less noise, at the cost of speed and latency. This is why a camera's photos get grainier in dim light at fast shutter speeds, and why the sorter gets less accurate as the belt speeds up.
Common mix-ups
A better sensor has no noise.
✓ Every sensor has noise; better ones have less, often by using more time, more light or more power.Software can always filter noise away.
✓ Filtering trades noise for lag and blurring, and cannot recover information the noise destroyed.
1.3 Signals: amplitude, frequency, period and SNR
A heartbeat, a wobbling arm and a humming motor all draw wiggly lines. Which three numbers describe each wiggle?
The sine wave
x(t) = A·sin(2πft + φ). Amplitude A is the swing from the middle to a peak (peak-to-peak is 2A). Frequency f is cycles per second, in hertz (Hz). Period T = 1/f is the time for one cycle. Phase φ shifts the wave in time. Most real signals are sums of sine waves at different frequencies.
Frequency tells you the source
A motor at 3000 rpm turns 50 times a second, so it shakes its mount at 50 Hz and its multiples. A walking robot's body bobs at its step rate. Knowing the frequency of the signal you want, and of the noise you don't, is the starting point for choosing a sample rate and a filter.
Signal-to-noise ratio
SNR compares the size of the signal with the size of the noise. Using RMS values (a sine's RMS is A/√2): SNR = RMS signal ÷ RMS noise, often quoted in decibels as 20·log₁₀(that ratio). 20 dB means the signal is 10× the noise; 0 dB means they are equal, and the signal is hard to see in a single look.
Common mix-ups
Amplitude is the distance from the lowest point to the highest.
✓ That is peak-to-peak, which is twice the amplitude.A signal with lower SNR is a weaker signal.
✓ SNR is a ratio: a strong signal with even stronger noise has low SNR.
1.4 Amplitude, frequency, phase
Two notes with exactly the same pitch and loudness can look completely different on an oscilloscope. Which one number changed?
Three numbers
x(t) = A·sin(2πft + φ). Amplitude A is the peak height. Frequency f (hertz) is cycles per second; the period T₀ = 1/f is the time for one cycle; angular frequency ω = 2πf is in radians per second. Phase φ says where in its cycle the wave is at t = 0. A phase of 90° turns a sine into a cosine.
Power is about the square
Average power over a period is the mean of x². For A·sin, sin² averages to 1/2, so P = A²/2. Add a constant offset D and P = D² + A²/2: the cross term 2DA·sin averages to zero. RMS = √P. UK mains is 230 V RMS, so its peak is 230·√2 ≈ 325 V.
Why sinusoids are special
Feed a sinusoid into a linear, time-invariant system (a spring, an RC circuit, a digital filter) and a sinusoid of the same frequency comes out, only scaled and shifted. That is why engineers describe systems by how they treat each frequency, and why the spectrum view you just used is so powerful.
Common mix-ups
Adding two sinusoids of the same frequency doubles the frequency.
✓ It gives one sinusoid of the same frequency; only the amplitude and phase change.RMS is the average of the signal.
✓ A sine's average is zero. RMS is the square root of the average of the square.
Examples to try
Worked solutions are in the interactive chapter online.
Signals: smooth waves and stored numbers: example 1
A light sensor's voltage swings between 0.9 V and 2.1 V and repeats every 10 ms (a flickering lamp). Middle, amplitude and frequency?
Where noise comes from: example 1
A sensor gives noise σ = 3 units at 0.4 m/s. Estimate σ at 1.6 m/s.
Signals: amplitude, frequency, period and SNR: example 1
x(t) = 0.3·sin(2π·25t) V with noise σ = 0.05 V. Find T, peak-to-peak and SNR in dB.
Amplitude, frequency, phase: example 1
v(t) = 2 + 4·sin(2π·50·t) V. Find its period, mean, average power (1 Ω) and RMS.
Interactive figures, in words
Figure 1.2 from “Signals: amplitude, frequency, period and SNR”
With sampling off, change amplitude and frequency and watch the period marker. Set f = 4 Hz and count the cycles in one second. Then add noise: at what σ does the wave become hard to see with A = 1? Note the SNR at that point.
The signal scope draws A·sin(2πft) over one second. With A = 1 and f = 4 Hz there are four full cycles; the green markers show the amplitude and one 250 ms period. Adding noise σ makes the trace fuzzy; at σ = 0.7 the SNR is about 0 dB and the wave is hard to pick out by eye.
Figure 1.3 from “Amplitude, frequency, phase”
Start from 'Pure tone'. Change the amplitude, then the frequency, then the phase of component 1, and watch both views. Which slider changes the spectrum bar's height, which moves it, and which changes neither?
The synthesiser adds three sinusoids. Amplitude changes the height of a component's spectrum bar, frequency moves the bar left or right, and phase changes the shape of the summed wave in time but leaves the bars and the power readout (sum of A²/2) unchanged.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Repeated distance measurements (Simulation OS experiment)
Record repeated readings of a fixed distance and estimate the noise level from their spread.
Open online - Equation Lab: Functions (Equation Lab exploration)
Change the amplitude, frequency and phase of a sine and describe what each one does to the graph.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A light sensor's readings jump every time a nearby motor starts. The most likely source is…
- thermal noise
- electrical interference
- quantisation
- bias
Check it in “Where noise comes from”
2. Which is usually the cheapest way to deal with interference?
- A heavy software filter
- Better wiring, shielding and grounding at the source
- A more expensive converter
Check it in “Where noise comes from”
3. A vibration has frequency 125 Hz. What is its period, in milliseconds?
Answer: ms
Check it in “Signals: amplitude, frequency, period and SNR”
4. A motor spins at 1800 rpm. At what frequency does an unbalance make it vibrate, in Hz?
Answer: Hz
Check it in “Signals: amplitude, frequency, period and SNR”
5. A signal's RMS is 100 times its noise RMS. What is the SNR in decibels?
Answer: dB
Check it in “Signals: amplitude, frequency, period and SNR”
6. One full cycle of a signal takes 1 ms. What is its frequency, in hertz?
Answer: Hz
Check it in “Signals: smooth waves and stored numbers”
7. A motor shaft vibrates at f = 25 Hz. What is its angular frequency ω, in rad/s (to 1 decimal place)?
Answer: rad/s
Check it in “Amplitude, frequency, phase”
8. UK mains is 230 V RMS. What is its peak voltage, in volts (nearest volt)?
Answer: V
Check it in “Amplitude, frequency, phase”
Engineering applications
Mains hum
Long unshielded sensor cables pick up the 50 or 60 Hz field from nearby mains wiring. Recognising that exact frequency in a noisy reading points straight at the cause: route the cable away or shield it.
Machine health
A healthy motor vibrates at frequencies tied to its speed. A new peak, or a growing one, is often the first sign of a worn bearing, long before anyone can hear it.
Summary
- A sinusoid is A·sin(2πft + φ): amplitude, frequency and phase.
- Period T = 1 / f and angular frequency ω = 2πf.
- For a sinusoid, RMS = A / √2; power depends on RMS, not peak.
- SNR compares signal power to noise power, often in decibels; fixing noise at its source beats filtering it later.
Glossary
- Frequency and period
- Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
- Logarithms and decibels
- A logarithm answers 'what power gives this number?'. Decibels use logarithms to express ratios: 10 log10 for power ratios and 20 log10 for amplitude ratios.
- Radians and degrees
- A radian is the angle at which the arc length equals the radius. A full turn is 2π radians, which is 360 degrees.
- Random and systematic error
- Random errors scatter readings unpredictably above and below the true value; systematic errors shift every reading the same way.
Project: Characterise a signal
Record or generate a noisy periodic signal, such as a vibration log or a synthetic sine with added noise. Estimate its frequency, amplitude, RMS value and signal-to-noise ratio, explain each method, and suggest the most likely source of the noise.
Deliverables
- A plot of the signal with the period marked
- Estimates of frequency, amplitude, RMS and SNR with working
- A short diagnosis of the noise source
References
- Alan V. Oppenheim et al. (1997). Signals and Systems, 2nd edition. Prentice Hall.
- Steven W. Smith (1997). The Scientist and Engineer's Guide to Digital Signal Processing. California Technical Publishing.
- Claude E. Shannon (1949). "Communication in the Presence of Noise". Proceedings of the IRE 37(1), 10–21.
2. Sampling and the Nyquist rate
A computer cannot store a smooth curve; it stores a list of numbers taken at regular instants. How often is often enough? Sample a sinusoid more than twice per cycle and its frequency can be recovered; sample less and the information is gone. That threshold, twice the highest frequency present, is the Nyquist rate. Engineers sample well above it, because real filters and real signals are never perfect.
Figure 2.1. Five samples per cycle (described in words)
A 10 Hz sine (dashed) sampled at 50 Hz, shown as stems and dots: 5 samples per cycle. The Nyquist rate for a 10 Hz signal is 20 Hz, and a 50 Hz sampler can represent frequencies up to 25 Hz.
Explanation
2.1 Sampling: how often is often enough?
In films, a fast car's wheels sometimes seem to spin backwards. What has that got to do with a temperature sensor?
Rate and period
The sample rate fs is samples per second (Hz); the sample period is the time between samples, 1 ÷ fs. A greenhouse logger sampling at 0.1 Hz takes one reading every 10 s; an audio recorder at 44,100 Hz takes one every 22.7 µs. Samples recorded = rate × duration: 50 Hz for 60 s gives 3,000 samples.
Samples per cycle
Divide the sample rate by the signal frequency to get samples per cycle. Ten or more show the wave's shape clearly. Between two and about five catch the frequency but the shape looks rough. Fewer than two per cycle cannot represent the wave at all. So a signal with frequency f needs a sample rate of more than 2f: half the sample rate is the highest frequency you can capture.
Aliasing and how to avoid it
When a signal is too fast for the sample rate, its samples line up into a slower, false wave: an alias. A 9 Hz wiggle sampled at 10 Hz pretends to be 1 Hz, and no maths afterwards can tell the difference. Engineers prevent it by sampling fast enough for every frequency present and by filtering out faster wiggles (like mains hum) before the ADC.
Common mix-ups
Sampling too slowly just makes the wave a bit rough.
✓ Below two samples per cycle the samples show a different, false frequency. That is worse than roughness: it is wrong information.You can fix aliasing later with clever software.
✓ Once aliased, the false wave looks exactly like a real slow one. Prevent it with a fast enough rate and a filter before sampling.
2.2 Sampling and the Nyquist rate
A computer can't watch a signal continuously; it takes snapshots. How many snapshots a second are enough to catch a 50 Hz hum?
Samples, not signals
A sampler measures the signal every Tₛ = 1/fₛ seconds, where fₛ is the sample rate in hertz. Between samples the computer knows nothing. Any two signals that agree at every sample instant are indistinguishable afterwards, however different they were in between.
The Nyquist rate
To capture a sine wave of frequency f, you need more than two samples per cycle: fₛ > 2f. For a signal whose highest frequency is f_max, the Nyquist rate is 2·f_max. Equivalently, a given fₛ can faithfully represent frequencies only up to fₛ/2, called the Nyquist frequency.
Margins in practice
Exactly 2f is a knife edge: sampled at the wrong phase, a wave right at the limit can vanish. Engineers sample with a comfortable margin, often 5–10 times the highest frequency of interest for control and monitoring, and use an analogue filter to remove anything above fₛ/2 before sampling.
Common mix-ups
Sampling at exactly twice the frequency is enough.
✓ You need more than twice; at exactly 2f a wave can vanish if sampled at its zero crossings.Sampling faster always gives better data.
✓ Above a comfortable margin it mostly adds cost, and noise above the band of interest still needs filtering.
2.3 From a wave to a list of numbers
Your phone's microphone hears a smooth, endless pressure wave. Your phone stores a list of whole numbers. What happened in between?
Two independent choices: time and value
A continuous-time signal x(t) has a value at every instant. A discrete-time signal x[n] exists only at the sample instants. Separately, a value can be analog (any real number) or quantised (one of a fixed set of levels). A digital signal is both discrete in time and quantised in value. The two steps are done by one chip, an ADC, but they cause different errors: sampling can cause aliasing, quantising adds rounding noise.
x[n] = x(nT)
Uniform sampling takes one value every T seconds; the sample rate is fs = 1/T. Sample n is the value at t = nT. The list x[0], x[1], x[2], … is all a processor ever sees. Square brackets mean an integer index; round brackets mean real time. Mixing them up is the commonest source of off-by-a-factor bugs in signal code.
Energy and power
For a sequence, energy E = Σ x[n]², the sum of squared samples (for a voltage across 1 Ω this is proportional to the energy delivered). Signals that go on for ever, like a sine wave, have infinite energy, so we use average power P = mean of x². A sinusoid of amplitude A has P = A²/2, and its RMS value √P = A/√2 is the steady voltage that would deliver the same power.
Common mix-ups
Digital just means sampled.
✓ Digital means sampled in time and quantised in value: two separate steps with two separate kinds of error.The sample index n is the time.
✓ n counts samples. Time is n·T = n/fs, so the same n means a different instant at a different sample rate.
2.4 How fast is fast enough?
Film a spinning wheel and it can appear to turn slowly backwards. Is the camera lying, or are you?
The sampling theorem
If a signal contains no frequencies at or above B, sampling at fs > 2B keeps all its information: the original can be rebuilt exactly from the samples (by ideal interpolation). fs/2 is called the Nyquist frequency; 2B is the Nyquist rate. Below that, information is lost and, worse, disguised.
Why twice?
To capture a sinusoid you need at least a high sample and a low sample in every cycle, more than two per period. At exactly two samples per cycle you might hit only the zero crossings and see nothing at all. That is why the inequality is strict.
Real systems add margin
CD audio samples at 44.1 kHz to cover hearing up to about 20 kHz: Nyquist is 22.05 kHz, leaving room for an anti-aliasing filter to roll off. Control loops often sample 10–20 times faster than the dynamics they control, because they need the signal's shape, not just its frequency.
Common mix-ups
Sampling at exactly twice the highest frequency is enough.
✓ You need strictly more than twice; at exactly 2B you can land on zero crossings and lose the signal.Frequencies above Nyquist are simply missed.
✓ They are not missed: they reappear at a false lower frequency (an alias).
Examples to try
Worked solutions are in the interactive chapter online.
Sampling: how often is often enough?: example 1
You want to measure 50 Hz mains hum on a sensor line. What is the slowest sample rate that could possibly capture it, and what would you actually choose?
Sampling: how often is often enough?: example 2
A logger samples at 250 Hz for 30 s. How many samples?
Sampling and the Nyquist rate: example 1
A wheel encoder produces pulses at up to 300 Hz. What is the Nyquist rate, and what would you choose?
From a wave to a list of numbers: example 1
x(t) = 3·cos(2π·2·t) is sampled at fs = 8 Hz. List x[0] to x[3].
From a wave to a list of numbers: example 2
What is the energy of x = [1, 2, −1, 0]?
How fast is fast enough?: example 1
An accelerometer measures vibrations up to 400 Hz. Which of 500 Hz, 1 kHz or 2 kHz would you choose?
Interactive figures, in words
Figure 2.2 from “Sampling: how often is often enough?”
Set the signal to 9 Hz and the sample rate to 10 Hz. Untick the real signal: what do the dots show? Now raise the sample rate until the readout stops warning you. How many samples per cycle did that take?
In the signal lab, a 9 Hz wave sampled 10 times a second gives dots that trace a slow 1 Hz wave: the readout warns that there are fewer than 2 samples per cycle. Raising the sample rate above 18 Hz removes the warning, and around 40–60 Hz the dots clearly follow the real wave's shape.
Figure 2.3 from “How fast is fast enough?”
Keep fs = 20 Hz. Raise f from 1 Hz slowly. At what f does the dashed 'what the samples show' curve stop matching the blue signal? Then set f = 20 Hz exactly and explain what you see.
In the sampler at fs = 20 Hz, the samples follow the signal faithfully until f reaches 10 Hz (the Nyquist frequency). Above that, the dots trace a slower false wave: at 12 Hz they look like 8 Hz. At exactly 20 Hz every sample has the same value, so the alias is 0 Hz.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Sample a 10 Hz sine at 15, 25 and 50 Hz and plot each set of samples against the original.
Open online - Simulation OS: Battery sensor node (Simulation OS experiment)
Halve the sample rate and see how much battery it saves; decide whether the signal survives.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A signal is sampled at fs = 1 kHz from t = 0. At what time, in seconds, is sample x[250] taken?
Answer: s
Check it in “From a wave to a list of numbers”
2. You sample a 1 Hz signal at 10 Hz. How many samples land in each cycle of the signal?
Answer: samples
Check it in “Sampling: how often is often enough?”
3. A sensor is sampled at 200 Hz. How long is the gap between samples, in milliseconds?
Answer: ms
Check it in “Sampling: how often is often enough?”
4. A data logger samples at 250 Hz. What is the highest frequency it can represent unambiguously (the Nyquist frequency), in Hz?
Answer: Hz
Check it in “Sampling and the Nyquist rate”
5. A 40 Hz vibration is sampled at 1 kHz. How many samples fall in each cycle?
Answer:
Check it in “Sampling and the Nyquist rate”
6. A signal's highest frequency is 300 Hz. Which sample rate is the smallest of these that works?
- 300 Hz
- 600 Hz
- 601 Hz
- 450 Hz
Check it in “How fast is fast enough?”
7. A control loop's fastest dynamics are at 8 Hz and the rule of thumb is to sample 20 times faster. What sample rate, in Hz?
Answer: Hz
Check it in “How fast is fast enough?”
Engineering applications
Audio
Human hearing tops out around 20 kHz, so CD audio samples at 44.1 kHz: a little over twice the highest frequency, with room for the filter that removes anything above it.
Battery versus bandwidth
Every sample costs energy and storage. A sensor node samples only as fast as its fastest interesting signal requires, with a margin, rather than as fast as it can.
Summary
- Sampling stores a signal's value every Ts seconds; the sample rate is fs = 1 / Ts.
- The Nyquist rate is twice the highest frequency in the signal.
- A sampler at fs can represent frequencies up to fs / 2, the Nyquist frequency.
- Practical systems sample comfortably above the Nyquist rate.
Glossary
- Sampling and aliasing
- Sampling measures a signal at regular intervals. Any frequency above half the sample rate, the Nyquist frequency, is indistinguishable from a lower 'alias' frequency.
- Frequency and period
- Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
- ADC resolution
- An n-bit analogue-to-digital converter splits its reference voltage into 2^n steps; one step, the least significant bit, is the smallest change it can detect.
Project: Choose a sample rate
Pick three signals a robot might measure, such as wheel speed, motor current and a microphone. Estimate the highest frequency each contains, choose a sample rate with a stated margin, and calculate the data rate each produces in bytes per second.
Deliverables
- A table of signals, highest frequencies and chosen rates
- The margin you chose and why
- The data rate for each signal
References
- Harry Nyquist (1928). "Certain Topics in Telegraph Transmission Theory". Transactions of the American Institute of Electrical Engineers 47(2), 617–644.
- Claude E. Shannon (1949). "Communication in the Presence of Noise". Proceedings of the IRE 37(1), 10–21.
- Alan V. Oppenheim and Ronald W. Schafer (2010). Discrete-Time Signal Processing, 3rd edition. Pearson.
3. Aliasing: when samples lie
Sample too slowly and a fast signal does not disappear; it disguises itself as a slow one. Wagon wheels in films turn backwards for the same reason. The alias frequency can be predicted exactly by folding the true frequency around multiples of the sample rate. Once aliased, no software can separate the impostor from a real signal, so the cure is an analogue low-pass filter before the sampler.
Figure 3.1. Same dots, two different waves (described in words)
A 900 Hz cosine (thin line) sampled at 1000 Hz. The samples, shown as dots, lie exactly on a 100 Hz cosine (thick line): the 900 Hz signal looks like 100 Hz.
Explanation
3.1 Aliasing: when samples tell lies
In films, car wheels sometimes spin backwards while the car speeds forwards. The camera isn't broken. What is it doing?
Aliasing in one sentence
When a signal contains frequencies above fₛ/2, sampling folds them down into the range 0 to fₛ/2, where they look exactly like genuine low-frequency signals. After sampling, nothing can tell them apart: the information is gone.
The wagon-wheel effect
A spoked wheel looks identical after turning by one spoke gap. If, between frames, it turns almost exactly one gap, it looks almost still; slightly less than a gap, it seems to creep backwards. Films at 24 fps, strobe lights and LED lighting that flickers at a fixed rate all create this illusion with real machines.
Preventing aliasing
Prevent it before sampling: an analogue anti-aliasing filter removes frequencies above fₛ/2, or you raise fₛ above twice the highest frequency present. A digital filter after sampling is too late: the alias is already mixed into the band you care about.
Derivation: Where the alias frequency comes from
Sample x(t) = sin(2πft) at instants t = k/fₛ: the samples are x[k] = sin(2πf·k/fₛ).
Add any whole number m of sample rates to the frequency: sin(2π(f + m·fₛ)·k/fₛ) = sin(2πf·k/fₛ + 2πmk). Since mk is a whole number, the extra 2πmk changes nothing.
So f, f ± fₛ, f ± 2fₛ, … all give identical samples: they are aliases of each other.
Also sin(−θ) = −sin(θ), so a frequency −a gives the same samples as +a with the phase flipped. Frequencies are indistinguishable from their mirror images too.
The sampler shows the alias closest to zero: f_alias = |f − k·fₛ|, where k·fₛ is the whole multiple of fₛ nearest to f. It always lies between 0 and fₛ/2.
Example: f = 23 Hz, fₛ = 10 Hz. The nearest multiple is 20 Hz, so f_alias = |23 − 20| = 3 Hz.
Wagon wheel: N identical spokes at r rev/s make a pattern repeating at N·r Hz. Filmed at F fps, it appears to turn at (signed alias of N·r at F) ÷ N rev/s. A negative alias means it seems to turn backwards.
Common mix-ups
Aliasing is a kind of random noise.
✓ It is a deterministic false signal, perfectly repeatable, which is what makes it so convincing.You can remove aliasing with a digital filter afterwards.
✓ Once folded, the alias sits inside the band you want. It must be filtered out before sampling.
3.2 Predicting the impostor
A 900 Hz whistle is recorded at 1 kHz. Play it back and you hear a low hum instead. Exactly what pitch, and why?
Folding
Picture the frequency axis folded like a paper fan at every multiple of fs/2. Any frequency lands somewhere in the first panel, 0 to fs/2. That landing place is the alias. With fs = 100 Hz: 30, 70, 130 and 170 Hz all land on 30 Hz.
Negative aliases and backwards wheels
A film camera at 24 frames/s filming a wheel turning 23 times per second sees it advance 23/24 of a turn per frame: indistinguishable from going back 1/24 of a turn. f − fs = −1 Hz: the wheel seems to turn backwards once per second. For a rotation the sign matters; for a cosine on a graph it does not.
Using the formula as a detective
If a log shows a mystery 30 Hz wobble and you sample at 100 Hz, candidates are 30, 70, 130, 170 Hz… Check the machine for anything at those frequencies, like a motor at 4200 rpm (70 Hz). If you find one, you have caught an alias, and the fix is filtering before sampling or sampling faster.
Derivation: The exact alias formula
Samples of x(t) = cos(2πft) are x[n] = cos(2π·(f/fs)·n).
Adding a whole number of cycles per sample changes nothing: cos(2π(f − k·fs)n/fs) = cos(2πfn/fs − 2πkn) = x[n] for every integer k.
Cosine is even, so a negative frequency gives the same samples as its magnitude: cos(−θ) = cos θ.
Choose k = round(f/fs) so that f − k·fs lies between −fs/2 and +fs/2.
Therefore f_alias = |f − round(f/fs)·fs|, always between 0 and fs/2. (For sine waves the sign of f − k·fs also flips the phase: that is the 'backwards' wheel.)
Common mix-ups
The alias is always fs − f.
✓ Only when f is between fs/2 and fs. In general subtract the nearest whole multiple of fs.Software can tell an alias from a real low frequency afterwards.
✓ The samples are identical. Only knowledge from outside (a filter, a faster sensor) can tell them apart.
3.3 Stopping aliases before they start
Every audio interface and many sensor boards put a filter in front of the ADC. If the ADC is digital, why does it need an analog guard?
Filter first, sample second
An anti-aliasing filter is a low-pass filter before the ADC that shrinks everything above fs/2 enough that its aliases are buried below the noise floor. Digital filtering after sampling cannot help: by then the alias sits at an allowed frequency and looks exactly like real signal.
The RC low-pass
A resistor in series and a capacitor to ground form the simplest low-pass. Its cut-off fc = 1/(2πRC) is where the output falls to 1/√2 (−3 dB). Above fc the gain falls roughly as fc/f: −20 dB per decade. With R = 1.6 kΩ and C = 100 nF, fc ≈ 995 Hz.
Oversample, then decimate
Real filters roll off gradually. A common trick: sample much faster than needed (oversample), so a gentle analog filter suffices, then use a sharp digital low-pass and keep every Mth sample (decimation). Delta-sigma audio ADCs work this way internally.
Common mix-ups
The cut-off frequency is where the filter blocks everything.
✓ At fc the gain is still 0.707. A first-order filter only reaches one tenth at ten times fc.
3.4 Choosing a sample rate for a real robot
Sampling at 10 kHz is safe but drains the battery. Sampling at 20 Hz is cheap but might lie. How do you pick?
Start from the frequencies
List what the signal contains: the frequencies you want (the tilt, the heartbeat, the wall getting closer) and the ones you don't (motor vibration, mains hum at 50 or 60 Hz, switching noise). The sample rate must exceed twice the highest frequency that reaches the sampler, wanted or not.
Filter, then sample
An analogue low-pass filter in front of the converter cuts unwanted high frequencies so they can't alias. A common digital pattern is oversample, filter, decimate: sample fast, low-pass filter digitally, then keep every Mth sample. The filter must run on the fast samples, before you throw any away.
Count the cost
Data rate = channels × sample rate × bytes per sample. Six 16-bit channels at 1 kHz is 12 kB/s, about 43 MB an hour. Processing cost scales the same way. Control loops also need the delay between sample and action to be small compared with the system's response time.
Common mix-ups
Choose the sample rate from the signal you want only.
✓ Everything that reaches the sampler counts, including vibration and interference you don't want.Keeping every 10th sample is a harmless way to save memory.
✓ It is sampling at a tenth of the rate and aliases unless you filter first.
Examples to try
Worked solutions are in the interactive chapter online.
Aliasing: when samples tell lies: example 1
A 130 Hz vibration is sampled at 100 Hz. What frequency appears?
Aliasing: when samples tell lies: example 2
A 5-spoke wheel turns at 4.6 rev/s, filmed at 24 fps. What do you see?
Predicting the impostor: example 1
A 4200 rpm fan is sampled by a 100 Hz sensor. What vibration frequency appears in the data?
Stopping aliases before they start: example 1
Choose C for an RC anti-aliasing filter with R = 10 kΩ and fc ≈ 160 Hz.
Choosing a sample rate for a real robot: example 1
Mains hum at 50 Hz leaks into a sensor sampled at 52 Hz. What appears?
Interactive figures, in words
Figure 3.2 from “Aliasing: when samples tell lies”
Set 6 spokes at 24 fps. Find a wheel speed where the wheel seems to stand still, one where it creeps forwards and one where it creeps backwards. Step frame by frame. Then use the readout to predict the next 'stand still' speed before you find it.
The wagon-wheel explorer shows six consecutive film frames of a spoked wheel. With 6 spokes at 24 fps: at 4 rev/s every frame looks identical (stand-still); at 3.8 rev/s the spokes step slightly backwards each frame; at 1 rev/s they step forwards by 15 degrees per frame. The readout gives the pattern frequency, the alias and the apparent speed.
Figure 3.3 from “Predicting the impostor”
Fix fs = 10 Hz. Step f through 3, 7, 13 and 17 Hz and write down the alias each time. What pattern do you see? Predict f = 23 Hz before you try it.
With fs = 10 Hz in the sampler: 3 Hz shows as 3 Hz, 7 Hz as 3 Hz, 13 Hz as 3 Hz and 17 Hz as 3 Hz, because each is 3 Hz away from a multiple of 10 Hz. 23 Hz also shows as 3 Hz.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write alias_of(f, fs) and check it against sampled sinusoids at five frequencies above fs / 2.
Open online - Simulation OS: Washing-machine spin cycle (Simulation OS experiment)
Find a drum speed at which a slow sampler would report a misleadingly slow vibration.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A 70 Hz signal is sampled at 50 Hz. What is the alias frequency, in Hz?
Answer: Hz
Check it in “Aliasing: when samples tell lies”
2. An 8-spoke wheel is filmed at 24 fps. What is the slowest non-zero speed at which it appears perfectly still, in rev/s?
Answer: rev/s
Check it in “Aliasing: when samples tell lies”
3. Your logged vibration shows a 30 Hz peak you suspect is an alias. What is the most convincing test?
- Average more data
- Change the sample rate: a real 30 Hz stays at 30 Hz, an alias moves
- Apply a digital low-pass filter at 40 Hz
Check it in “Aliasing: when samples tell lies”
4. A 900 Hz whistle is sampled at 1 kHz. What alias frequency, in Hz, appears?
Answer: Hz
Check it in “Predicting the impostor”
5. Sampled at fs = 100 Hz, which frequency gives exactly the same samples as a 20 Hz cosine?
- 40 Hz
- 80 Hz
- 120 Hz
- Both 80 Hz and 120 Hz
Check it in “Predicting the impostor”
6. An RC low-pass has R = 1.6 kΩ and C = 100 nF. What is fc = 1/(2πRC), in Hz (nearest 5 Hz)?
Answer: Hz
Check it in “Stopping aliases before they start”
7. Why can't a digital filter after the ADC remove aliases?
- Digital filters are too slow
- After sampling, an alias is indistinguishable from a real signal at that frequency
- Digital filters only work on audio
- It can, if it has enough taps
Check it in “Stopping aliases before they start”
8. Mains hum at 50 Hz is sampled at 45 Hz. At what frequency does it appear, in Hz?
Answer: Hz
Check it in “Choosing a sample rate for a real robot”
Engineering applications
Rolling shutters
Phone cameras read the image row by row, so fast propellers and guitar strings appear bent or frozen. It is aliasing in space and time, and no editing afterwards can recover the true motion.
Anti-aliasing filters
Data acquisition boards put an analogue low-pass filter in front of every ADC. It removes frequencies the sampler cannot represent before they can fold down and pollute the measurement.
Summary
- Frequencies above fs / 2 fold back and appear as lower alias frequencies.
- Alias = |f − round(f / fs) × fs|; for 900 Hz at 1000 Hz it is 100 Hz.
- Aliased samples are identical to a real low-frequency signal, so the damage cannot be undone digitally.
- Prevent aliasing with an analogue low-pass filter before sampling, plus a higher sample rate.
Glossary
- Sampling and aliasing
- Sampling measures a signal at regular intervals. Any frequency above half the sample rate, the Nyquist frequency, is indistinguishable from a lower 'alias' frequency.
- Low-pass filter (moving average and EMA)
- A low-pass filter lets slow changes through and attenuates fast ones. In firmware the simplest are the moving average and the exponential moving average.
- Frequency and period
- Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
Project: Catch an alias
Simulate a vibration sensor that sees a 120 Hz motor whine but samples at only 100 Hz. Predict the alias, show it in a plot of the samples, then design the cheapest fix: a filter cut-off, a new sample rate or both. Justify your choice with numbers.
Deliverables
- The predicted alias frequency with working
- A plot showing the alias in the samples
- The chosen fix with its cut-off or rate
References
- Alan V. Oppenheim and Ronald W. Schafer (2010). Discrete-Time Signal Processing, 3rd edition. Pearson.
- Richard G. Lyons (2010). Understanding Digital Signal Processing, 3rd edition. Prentice Hall.
- Harry Nyquist (1928). "Certain Topics in Telegraph Transmission Theory". Transactions of the American Institute of Electrical Engineers 47(2), 617–644.
4. Quantisation and resolution
After sampling in time comes rounding in value. An ADC has a fixed number of bits, so every reading is rounded to the nearest of 2^n levels. That rounding adds a small, predictable error, quantisation noise, and every extra bit roughly halves it. Resolution is not accuracy: a 16-bit sensor that reads 2 °C high is precise and wrong. Choosing the range wisely matters as much as the bit count.
Figure 4.1. 3 bits → 8 levels (described in words)
A 3-bit quantiser over 0 to 8 V drawn as a staircase beside the ideal straight line: 8 levels, 1 V apart. The rounding noise has RMS value step/√12 = 0.289 V, and the ideal signal-to-quantisation-noise ratio is about 19.8 dB.
Explanation
4.1 Range, resolution and the bits behind them
A 10-bit and a 16-bit sensor both measure 0–5 V. One sees changes 64 times smaller. Does that make it 64 times more accurate?
Range: what it can see at all
The range is the span of inputs a sensor reports faithfully, for example 0–5 V or 2–400 cm. Outside it the output saturates: it sticks at the end value. A saturated reading is the most dangerous kind, because it looks like a normal number. Choose a range that covers the largest value you could meet, with some margin.
Resolution: the smallest step
A converter with n bits has 2ⁿ codes. Spread over the range, each step is range ÷ 2ⁿ wide (some datasheets divide by 2ⁿ − 1; the difference is tiny for large n). A 12-bit converter on 0–3.3 V has steps of 3.3 ÷ 4096 ≈ 0.81 mV. Every reading carries an extra uncertainty of up to one step, called quantisation error.
Resolution is not accuracy
Resolution says how finely the sensor divides the range. Accuracy says how close the reported value is to the truth. A sensor with a gain error, an offset or a bow in its response can report confidently in tiny steps and still be wrong by a lot. Extra bits help only when quantisation is the biggest error.
Reading a spec line
'Range 0–40 °C, resolution 0.01 °C, accuracy ±0.5 °C' tells you the readings move in hundredths but can be half a degree off. For a greenhouse that is fine; for a medical thermometer it is not. Always ask which number limits your task.
Common mix-ups
More decimal places on the display mean a more accurate sensor.
✓ Decimal places show resolution. Accuracy comes from calibration and the sensor's physics, and is stated separately on the datasheet.A sensor at the top of its range is just measuring a big value.
✓ It may be saturated: the true value could be anything above the limit.
4.2 Rounding to the nearest step
Why does a 16-bit recording sound clean but an 8-bit one hiss, when both sample just as fast?
Steps and codes
An ideal N-bit ADC splits its input range V into 2^N equal steps of size Δ = V/2^N and outputs the code of the step the input falls in. A 12-bit ADC on a 3.3 V range has Δ = 3.3/4096 ≈ 0.81 mV. A rounding quantiser is never more than Δ/2 away from the truth.
Error behaves like noise
For a signal that wanders across many steps, the rounding error looks like random noise spread evenly between ±Δ/2, with power Δ²/12. That is why quantisation is often called quantisation noise, and why the SNR formula works. It fails for very slow or tiny signals, where the error follows the signal and shows up as distortion instead.
Use the whole range
The formula assumes a full-scale sine. A signal using a quarter of the range has 1/16 of the power but the same Δ, so it loses 20·log₁₀ 4 ≈ 12 dB: two bits' worth. Engineers add an amplifier in front of the ADC so the signal fills the range without clipping.
Derivation: Where 6.02N + 1.76 dB comes from
An N-bit quantiser spanning a full range of 2A (from −A to +A) has step Δ = 2A/2^N.
Rounding error e lies between −Δ/2 and +Δ/2. If it is spread evenly (true for busy signals), its mean square is σₑ² = Δ²/12.
A full-scale sine of amplitude A has power P = A²/2.
SNR = P/σₑ² = (A²/2) / (4A²/(12·4^N)) = 1.5 · 4^N.
In decibels: 10·log₁₀(1.5) + N·10·log₁₀(4) = 1.76 + 6.02N dB.
Common mix-ups
A faster sample rate fixes quantisation noise.
✓ Sample rate decides which frequencies you capture; bit depth decides the rounding error. They are separate knobs (oversampling helps only when combined with filtering).Any 16-bit ADC gives 98 dB.
✓ That is the ideal full-scale figure. Small signals and real-world noise give less.
4.3 Range, resolution, accuracy, precision
A thermometer shows 21.37 °C. Does all that detail mean it is right?
Range and resolution
Range is the span a sensor can measure, such as −40 to 125 °C. Outside it, readings are wrong or clipped. Resolution is the smallest change it can report, such as 0.5 °C. A 0–100 °C sensor with 0.5 °C resolution can report 100 ÷ 0.5 + 1 = 201 different values.
Accuracy and precision
Accuracy is how close readings are to the true value. Precision is how close repeated readings are to each other. Picture darts: a tight cluster off-centre is precise but inaccurate; a loose spread around the bullseye is accurate on average but imprecise. Calibration fixes consistent offsets; averaging reduces scatter.
Decimal places are not truth
A display showing 21.37 °C has fine resolution, but if the datasheet says ±2 °C accuracy, the true value could be anywhere from about 19.4 to 23.4 °C. Always report a measurement with an honest uncertainty, and never trust digits beyond what the datasheet promises.
Common mix-ups
More decimal places means a more accurate sensor.
✓ Decimal places show resolution. Accuracy is a separate figure on the datasheet.Accuracy and precision are the same thing.
✓ Precision is agreement between readings; accuracy is closeness to the truth.
Examples to try
Worked solutions are in the interactive chapter online.
Range, resolution and the bits behind them: example 1
A 10-bit ADC spans 0–3.3 V. What is one step, and what code does 1.00 V give?
Range, resolution and the bits behind them: example 2
A load cell's amplifier outputs 0–2 V and you want 0.1 mV steps. How many bits?
Rounding to the nearest step: example 1
An 8-bit ADC spans 0–5 V. Find Δ, the maximum error and the best-case SNR.
Rounding to the nearest step: example 2
You need 70 dB of SNR. How many bits?
Range, resolution, accuracy, precision: example 1
A distance sensor measures 2 cm to 400 cm with 1 cm resolution and ±3 cm accuracy. It reports 150 cm. What can you honestly say?
Interactive figures, in words
Figure 4.2 from “Range, resolution and the bits behind them”
Start at 4 bits and slide the true input slowly: the reading jumps in steps. Raise the bits and watch the staircase shrink. Then push the input past the top of the range, and finally add bow. Which problems do extra bits fix, and which don't they touch?
The diagram plots the reported voltage against the true input as a staircase. With 4 bits the steps are 0.31 V tall on a 5 V range; with 12 bits they are 1.2 mV and the staircase looks like a straight line. Inputs above the top of the range all read the maximum code (saturation). Adding bow curves the staircase away from the straight line by up to bow × range ÷ 4, an error extra bits cannot remove.
Figure 4.3 from “Rounding to the nearest step”
Start at 3 bits and full amplitude. Note the measured SNR, then add bits one at a time. Then go back to 8 bits and turn the amplitude down to 0.25. How many dB do you lose, and how many bits is that worth?
The quantiser shows a sine wave and its staircase approximation. With 3 bits there are 8 levels and the measured SNR is about 20 dB; every extra bit adds about 6 dB, matching 6.02N + 1.76. Reducing the amplitude to 0.25 of full scale costs about 12 dB.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Quantise a slow sine with 3, 6 and 10 bits and compare the RMS rounding error with step / √12.
Open online - Simulation OS: Encoder resolution (Simulation OS experiment)
Halve the encoder resolution and measure how much the tool-tip uncertainty grows.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. How many distinct codes does a 12-bit converter have?
Answer:
Check it in “Range, resolution and the bits behind them”
2. A sensor has a ±2% gain error. Upgrading its converter from 10 to 16 bits will…
- remove the gain error
- make readings finer-grained but still up to 2% off
- make the readings less precise
Check it in “Range, resolution and the bits behind them”
3. A sensor outputs 0–0.5 V into a 10-bit converter spanning 0–5 V. How many of the 1024 codes can it actually use?
Answer: codes
Check it in “Range, resolution and the bits behind them”
4. An ideal 10-bit ADC spans 0 to 3.3 V. What is its step Δ, in millivolts (to 2 decimal places)?
Answer: mV
Check it in “Rounding to the nearest step”
5. Adding one bit to an ideal ADC…
- Halves Δ and adds about 6 dB of SNR
- Halves Δ and doubles the SNR in dB
- Adds 1 dB
- Only matters for slow signals
Check it in “Rounding to the nearest step”
6. When does 'quantisation error behaves like even, random noise' break down?
- For a loud, busy music signal
- For a very slow signal that changes by less than one step
- Never
- When N is large
Check it in “Rounding to the nearest step”
7. A sensor covers 0 to 50 °C with a resolution of 0.25 °C. How many distinct values can it report?
Answer:
Check it in “Range, resolution, accuracy, precision”
8. A sensor with ±1.5 °C accuracy reads 18.0 °C. What is the lowest temperature the true value could be, in °C?
Answer: °C
Check it in “Range, resolution, accuracy, precision”
Engineering applications
Digital audio
Each extra bit of audio adds about 6 dB of dynamic range. Sixteen bits give enough range for quiet passages to stay clear of the rounding hiss, which is why it became the standard for CDs.
Wasted range
A 0–50 V input range used to read a 0–3 V sensor throws away most of the codes. Scaling the signal to fill the ADC's range gives far finer steps from the same converter.
Summary
- An n-bit ADC has 2^n levels; the step is range / 2^n.
- Rounding error is at most half a step; modelled as noise, its RMS is step / √12.
- Each extra bit halves the step and adds about 6 dB of signal-to-quantisation-noise ratio.
- Resolution is not accuracy: bias and calibration errors are separate from rounding.
Glossary
- ADC resolution
- An n-bit analogue-to-digital converter splits its reference voltage into 2^n steps; one step, the least significant bit, is the smallest change it can detect.
- Accuracy, precision and resolution
- Accuracy is how close a measurement is to the true value; precision is how close repeated measurements are to each other; resolution is the smallest change an instrument can show.
- Logarithms and decibels
- A logarithm answers 'what power gives this number?'. Decibels use logarithms to express ratios: 10 log10 for power ratios and 20 log10 for amplitude ratios.
- Binary place value
- In binary each digit position is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. A number's value is the sum of the place values that hold a 1.
Project: How many bits?
A load cell outputs 0 to 20 mV for 0 to 10 kg, and you need to resolve 5 g. Decide on amplifier gain, ADC range and bit count, compute the step in grams, and explain the difference between the resolution you achieve and the accuracy you can claim.
Deliverables
- The signal chain with gain, range and bits
- The step size in grams
- A paragraph on resolution versus accuracy for this design
References
- Steven W. Smith (1997). The Scientist and Engineer's Guide to Digital Signal Processing. California Technical Publishing.
- Richard G. Lyons (2010). Understanding Digital Signal Processing, 3rd edition. Prentice Hall.
5. Smoothing filters
Noisy readings tempt you to average. A moving average of the last N samples cuts random noise but makes every change appear late. The exponential filter keeps just one number of memory and blends each new reading in with a weight α; small α means smooth and slow. A single spike can still drag an average a long way, which is when a median filter earns its place. Inside a control loop, every bit of lag has a cost.
Figure 5.1. Smoothing costs lag (described in words)
The response of two smoothers to a sudden step from 0 to 1. An exponential filter with α = 0.5 gives 0.5, 0.75, 0.875, 0.9375; a 4-point moving average gives 0.25, 0.5, 0.75, 1 and only reaches the new value after four samples.
Explanation
5.1 The moving average and the noise–lag trade-off
Average the last 20 readings and the jitter melts away. So why does the robot now brake late?
How it works
A moving average of window k outputs the mean of the most recent k readings: yₙ = (xₙ + xₙ₋₁ + … + xₙ₋ₖ₊₁) ÷ k. Each new reading pushes the oldest out. It is cheap: keep a running sum, add the new value, subtract the one leaving.
Noise falls like √k
If the noise in each reading is independent with standard deviation σ, averaging k of them leaves about σ/√k. A window of 4 halves the noise; 16 quarters it. Noise that is not independent (a slow drift, a vibration at a steady frequency) is reduced less, or not at all.
Lag grows like k
The output describes the average of the last k samples, centred about (k − 1)/2 samples in the past. After a sudden change it takes k samples to catch up fully. At 100 samples a second, a 21-sample window responds about 0.1 s late, which at 2 m/s is 20 cm.
Common mix-ups
A bigger window is always better because it is smoother.
✓ Every extra sample of smoothing is extra delay; the right window depends on how fast the signal really changes.A moving average removes all noise eventually.
✓ It reduces independent noise by √k and leaves slow drifts and bias untouched.
5.2 The exponential filter: one number of memory
A filter that remembers just one number can still 'remember' every reading it has ever seen. How?
One line of code
y = y + alpha * (x - y). The output moves a fraction α of the way towards each new reading. α = 1 copies the input (no filtering); α near 0 barely moves (heavy smoothing). Only one number, y, is stored.
Fading memory
Unrolled, the EMA is a weighted average of all past readings, with weights shrinking by a factor (1 − α) per step. Recent readings matter most; old ones fade but never quite disappear. That gives a smooth response with a quick initial reaction to a change.
Choosing α
Smaller α: less noise, more lag. A rough match to a k-sample moving average is α ≈ 2/(k + 1). If readings arrive every Δt seconds, the filter's time constant is about Δt/α; changes much faster than that are smoothed away.
Start-up and units
Initialise y with the first reading, not zero, or the output will spend many steps climbing from nothing. If the sample rate changes, α must change too to keep the same time constant.
Derivation: Unrolling the exponential filter
Start from yₙ = yₙ₋₁ + α(xₙ − yₙ₋₁) = αxₙ + (1 − α)yₙ₋₁.
Substitute the same rule for yₙ₋₁: yₙ = αxₙ + (1 − α)[αxₙ₋₁ + (1 − α)yₙ₋₂].
Keep going: yₙ = αxₙ + α(1 − α)xₙ₋₁ + α(1 − α)²xₙ₋₂ + α(1 − α)³xₙ₋₃ + …
Each older reading's weight is (1 − α) times the next newer one's: a geometric sequence. The weights add to α × 1/(1 − (1 − α)) = 1, so the output is a true weighted average.
Old readings never quite vanish, but they fade: after m steps a reading's weight has shrunk by (1 − α)ᵐ. With α = 0.2, after 10 steps it is 0.8¹⁰ ≈ 0.11 of its starting weight.
For a unit step the output after m samples is 1 − (1 − α)ᵐ. It reaches 90% when (1 − α)ᵐ = 0.1, so m = ln(0.1)/ln(1 − α): about 10.3 samples for α = 0.2.
For independent noise σ, the output's noise is σ·√(α/(2 − α)). α = 0.2 gives about 0.33σ, similar to a 9-sample moving average (σ/3). The two are roughly matched when k ≈ 2/α − 1.
Common mix-ups
An EMA forgets readings older than some window.
✓ Every past reading keeps a (shrinking) weight; there is no hard edge.α is a fixed property of the filter regardless of sample rate.
✓ The same α at a faster sample rate gives a shorter time constant; adjust α when you change the rate.
5.3 Spikes, median filters and filtering inside a controller
One glitch reading of 85 °C in a greenhouse at 18 °C. An average says 24 °C. What does the plant actually feel?
The median ignores outliers
A median filter outputs the middle value of the last k readings. A spike shorter than half the window lands at one end of the sorted list and is ignored, while real steps still pass through (after a delay of about half the window). Averages, by contrast, spread a spike's error over the whole window.
Filters live inside loops
In a feedback loop the controller acts on the filtered reading. Lag in the filter means the controller sees the world late: it keeps heating after the target is reached and overshoots. A filter that looks perfect on a recorded log can make a live loop oscillate.
Smoothing versus hysteresis
An on/off thermostat near its setpoint chatters as noise crosses the threshold back and forth. Heavy smoothing reduces chatter but adds lag. Hysteresis (switch on below one temperature, off above a higher one) stops chatter without lag, because noise smaller than the gap cannot cross both thresholds.
Common mix-ups
Every filter is a kind of average.
✓ The median is not an average; it is a ranking, which is why it can ignore outliers that averages can't.If a filter makes the plot look nicer, the controller will work better.
✓ Inside a loop, lag can make control worse even when the trace looks smoother.
Examples to try
Worked solutions are in the interactive chapter online.
The moving average and the noise–lag trade-off: example 1
Readings: 12, 15, 11, 18, 14. Window k = 3. What is the latest output?
The exponential filter: one number of memory: example 1
α = 0.5, y starts at 10. Readings 20, 20, 20. Outputs?
Spikes, median filters and filtering inside a controller: example 1
A 3-sample median over readings 5, 5, 40, 6, 6. Outputs from the third reading onward?
Interactive figures, in words
Figure 5.2 from “The moving average and the noise–lag trade-off”
Use the Step signal and hide the EMA and median. Try windows of 1, 5, 15 and 25. For each, write down the 'noise left' and the 'lag' from the readout. Plot the two numbers against each other in your notes: what shape does the trade-off make?
The filter tuner plots 120 noisy samples of a step from 0 to 1 at sample 40. A moving average with k = 1 follows the noise exactly; with k = 5 noise drops by about √5 and the step takes about 5 samples to rise; with k = 25 the line is very smooth but takes about 23 samples to reach 90% of the step.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Two-sensor fusion (Simulation OS experiment)
Smooth the noisy camera reading with an exponential filter and see how the lag affects the fused estimate.
Open online - Code Lab (Studio)
Apply a moving average, an exponential filter and a median filter to a log with one spike, and compare.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Readings 4, 8, 6, 10. What does a k = 2 moving average output now?
Answer:
Check it in “The moving average and the noise–lag trade-off”
2. Raw noise is σ = 6 mm. Roughly what noise remains after a 9-sample moving average (independent noise)?
Answer: mm
Check it in “The moving average and the noise–lag trade-off”
3. A 21-sample moving average runs at 50 samples per second. Using a delay of (k − 1)/2 samples, how late is its output, in seconds?
Answer: s
Check it in “The moving average and the noise–lag trade-off”
4. y = 50, new reading 40, α = 0.1. What is the new output?
Answer:
Check it in “The exponential filter: one number of memory”
5. With α = 0.25, what weight does the reading from 2 steps ago carry in the current output?
Answer:
Check it in “The exponential filter: one number of memory”
6. A temperature EMA starts with y = 0 °C, but the room is 21 °C. What happens?
- Nothing: the first reading fixes it
- The output climbs slowly from 0 and reports far too cold for a while
- The filter becomes unstable
Check it in “The exponential filter: one number of memory”
7. What is the median of 12, 97, 11, 13, 12?
Answer:
Check it in “Spikes, median filters and filtering inside a controller”
8. Adding a heavy filter to a heater's temperature reading most likely causes…
- faster warm-up
- more overshoot, because the controller sees changes late
- lower energy use, always
Check it in “Spikes, median filters and filtering inside a controller”
Engineering applications
Fuel gauges
Fuel sloshes as a car corners, so the raw tank reading jumps about. Gauges filter heavily, so the needle moves smoothly, accepting that it lags behind the true level by a minute or so.
Glitchy sensors
Ultrasonic rangers sometimes return a wild echo. A short median filter throws such outliers away entirely, where a mean would let one bad reading shift the estimate.
Summary
- A moving average of N samples reduces random noise by about √N and lags by about (N − 1) / 2 samples.
- The exponential filter is y = y + α(x − y): one number of memory, tuned by α.
- Median filters reject isolated spikes that would drag a mean.
- Every smoother trades noise for lag, and lag inside a control loop can cause overshoot.
Glossary
- Low-pass filter (moving average and EMA)
- A low-pass filter lets slow changes through and attenuates fast ones. In firmware the simplest are the moving average and the exponential moving average.
- Mean and median
- The mean is the sum of the values divided by how many there are; the median is the middle value once the values are sorted.
- Standard error of the mean
- The standard error of the mean estimates how much a sample mean would vary between repeated experiments: the sample standard deviation divided by the square root of the number of readings.
- Outliers and honest data
- An outlier is a reading far from the rest. It may be a genuine effect or a fault; either way it must be investigated and reported, and any exclusion rule decided before seeing the results.
Project: Tune a smoother
Take a noisy log from a range sensor approaching a wall. Choose a moving average length, an exponential α and a median window, apply each, and measure both the remaining noise and the lag when the robot stops. Recommend one filter for a robot that must brake in time.
Deliverables
- Plots of the raw and three filtered signals
- A table of noise and lag for each filter
- A recommendation with its trade-off stated
References
- Steven W. Smith (1997). The Scientist and Engineer's Guide to Digital Signal Processing. California Technical Publishing.
- Richard G. Lyons (2010). Understanding Digital Signal Processing, 3rd edition. Prentice Hall.
6. Sinusoids and Fourier series
Add sinusoids together and you can build almost any repeating shape. A spectrum is the recipe: a bar for each ingredient frequency, its height the amplitude. A square wave, all sharp corners, turns out to be odd harmonics only, with amplitudes falling as one over the harmonic number. Seeing signals as sums of sinusoids is the change of viewpoint that makes filters, music and radio understandable.
Figure 6.1. A square wave is odd harmonics only (described in words)
The spectrum of a unit square wave: bars only at odd harmonics, with amplitude 4/(πk). k = 1: 1.273, k = 3: 0.424, k = 5: 0.255, k = 7: 0.182; even harmonics are absent.
Explanation
6.1 Seeing a signal's ingredients
A chord played on a piano is one wobbly line on an oscilloscope. How can a tuner app name every note in it?
Two views of one signal
The time domain shows value against time. The frequency domain shows how much of each frequency is present. A magnitude spectrum draws a bar of height Aᵢ at each fᵢ. The same information, arranged differently, like a recipe versus the cake.
Phase hides in the time view
Shifting a component's phase reshapes the waveform (peaks can line up or cancel) but leaves its bar the same. That is why two signals that look different can sound identical: your ear cares mostly about magnitudes. A full description keeps the phase too, so the time signal can be rebuilt.
Power adds across frequencies
Sinusoids of different frequencies average to zero when multiplied together, so the cross terms vanish and P = Σ Aᵢ²/2. That is Parseval's theorem in miniature: power computed in time equals power computed from the spectrum. Components at the same frequency are different: they combine as phasors first.
Common mix-ups
If two waveforms look different, their spectra must be different.
✓ Phase changes the look without changing the magnitude spectrum.Amplitudes always add.
✓ Only powers of different frequencies add simply; same-frequency components add as phasors.
6.2 A square wave made of curves
A square wave has perfectly sharp corners. Sine waves have none. Yet enough sine waves add up to a square. How many, and what's left over?
The series
A square wave swinging between +A and −A is x(t) = (4A/π)·[sin ωt + sin 3ωt/3 + sin 5ωt/5 + …]. Harmonic n has amplitude bₙ = 4A/(nπ) for odd n and 0 for even n. The fundamental is 4/π ≈ 1.27 times taller than the square itself.
Power is concentrated low
The square has power A². The fundamental alone carries (4A/π)²/2 = 8A²/π² ≈ 81 % of it; adding the 3rd and 5th reaches about 93 %. So a square wave through a low-pass filter quickly looks like a sine: that is how some cheap sine-wave inverters work.
Gibbs: the overshoot that won't go away
Near each jump the partial sum overshoots by about 9 % of the jump, however many terms you add. More terms make the overshoot narrower, not lower. In practice, ringing near edges in a band-limited system is the same effect: a sharp edge truly needs infinitely high frequencies.
Common mix-ups
Enough harmonics make a perfect square wave with no overshoot.
✓ The partial sums always overshoot by about 9 % near jumps; only the width shrinks.The fundamental of a ±1 square wave has amplitude 1.
✓ It is 4/π ≈ 1.27: taller than the square, with the harmonics trimming it back down.
Examples to try
Worked solutions are in the interactive chapter online.
Seeing a signal's ingredients: example 1
Sketch the spectrum of 3 + 2·cos(2π·10t) + sin(2π·30t).
A square wave made of curves: example 1
A ±5 V, 1 kHz square wave drives a speaker. What is the amplitude of the 3 kHz component?
Interactive figures, in words
Figure 6.2 from “Seeing a signal's ingredients”
Load 'Three tones'. Read the spectrum bars, then change each phase and watch the time plot. Next put two components at the same frequency and vary one phase: what happens to that bar now?
With three tones at 2, 5 and 8 Hz the spectrum shows three bars of heights 1, 0.6 and 0.3. Changing phases changes the waveform's shape but not the bars. Putting two components at the same frequency makes one bar whose height depends on their phase difference (from the sum to the difference of the amplitudes).
Figure 6.3 from “A square wave made of curves”
Start with 1 harmonic, then add them one by one up to 25. Watch the power captured and the peak of the sum. Does the overshoot near the jump get smaller, or only narrower?
With 1 harmonic the builder draws a sine of peak 1.27 over the square. Adding odd harmonics (3, 5, 7…) fills in the corners; captured power rises from 81 % to about 98 % with 13 terms; the peak near each jump stays about 1.18, a 9 % overshoot of the jump of 2.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Add the first one, three and ten odd harmonics of a square wave and plot how the corners sharpen.
Open online - Equation Lab: Functions (Equation Lab exploration)
Add two sines of different frequency and amplitude and sketch the spectrum of the result.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. You change only the phase of one component. What changes?
- The height of its spectrum bar
- The waveform's shape in time
- The total power
- The component's frequency
Check it in “Seeing a signal's ingredients”
2. 3·sin(2π·5t) + 4·sin(2π·5t + 90°) is a single 5 Hz sinusoid. What is its amplitude?
Answer:
Check it in “Seeing a signal's ingredients”
3. Where does a constant offset appear in a spectrum?
- At the highest frequency
- Nowhere
- At 0 Hz
- Spread evenly over all frequencies
Check it in “Seeing a signal's ingredients”
4. What is the amplitude of the fundamental of a ±1 square wave (3 decimal places)?
Answer:
Check it in “A square wave made of curves”
5. What is the amplitude of the 4th harmonic of a symmetric square wave?
- 4A/(4π)
- Zero
- Half the 2nd harmonic
- The same as the 3rd
Check it in “A square wave made of curves”
6. What percentage of a square wave's power is in its fundamental alone (8/π² as a percentage, 1 decimal place)?
Answer: %
Check it in “A square wave made of curves”
7. You add more and more harmonics. What happens to the overshoot near each jump?
- It shrinks to zero
- It stays about 9 % of the jump but gets narrower
- It grows without limit
- It moves to the middle of the flat parts
Check it in “A square wave made of curves”
Engineering applications
Musical timbre
A flute and a violin playing the same note share a fundamental frequency but carry different mixtures of harmonics. That recipe, the spectrum, is what makes them sound different.
Switching interference
PWM and digital clocks are square-ish waves, so they radiate energy at many odd harmonics. Engineers check those harmonics against radio-interference limits and slow the edges if needed.
Summary
- A spectrum lists the amplitude (and phase) of each sinusoid in a signal.
- Sinusoids of the same frequency combine into one sinusoid of that frequency.
- A square wave contains only odd harmonics, with amplitude 4 / (πk).
- Truncated Fourier series overshoot near jumps: the Gibbs effect does not vanish with more terms.
Glossary
- Frequency and period
- Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
- Sine, cosine and tangent
- In a right-angled triangle, sine is opposite over hypotenuse, cosine is adjacent over hypotenuse and tangent is opposite over adjacent, each a function of the angle.
Project: Build a waveform from recipes
Write a program that synthesises a waveform from a list of (frequency, amplitude, phase) ingredients. Use it to approximate a square wave and a sawtooth, plot each with 3, 10 and 30 terms, and measure how the Gibbs overshoot behaves as terms are added.
Deliverables
- The synthesiser program
- Plots for both waveforms at three term counts
- Overshoot measurements and an explanation
References
- Alan V. Oppenheim et al. (1997). Signals and Systems, 2nd edition. Prentice Hall.
- Steven W. Smith (1997). The Scientist and Engineer's Guide to Digital Signal Processing. California Technical Publishing.
7. The DFT: measuring a spectrum
Given a list of samples, the discrete Fourier transform asks one question per frequency bin: how much of this wave is in the signal? It answers by correlating the samples with a test sinusoid. The bins are spaced by the sample rate divided by the number of samples, so a longer recording resolves finer detail. Transforms like this let engineers change the question, from "what happens next?" to "which frequencies are there?"
Figure 7.1. Bin spacing = fs / N (described in words)
DFT bins 0 to 10 drawn as bars, with bin 5 highlighted. With N = 100 samples at 1000 Hz the bins are 10 Hz apart, so bin 5 is 50 Hz and the last useful bin, 50, is 500 Hz.
Explanation
7.1 The DFT: asking 'how much of this wave?'
A computer only has eight numbers from a sensor. How can it say there is a strong 250 Hz component in them?
Correlation with probes
X[k] = Σ x[n]·cos(2πkn/N) − j·Σ x[n]·sin(2πkn/N). Each bin multiplies the signal by a probe wave with k cycles in the window and adds up. If the signal contains that wave, products are mostly positive and the sum is big; otherwise positives and negatives cancel. The cosine and sine sums together catch the component whatever its phase.
Bins and frequencies
With N samples at rate fs, bin k corresponds to f = k·fs/N. Resolution is fs/N: to tell close frequencies apart, record for longer. For a real signal, bins above N/2 mirror those below (they are the negative frequencies). A pure cosine of amplitude A exactly on bin k gives |X[k]| = A·N/2.
Small enough to do by hand
For N = 4 the probes take only the values 1, 0 and −1, so X[0] = x0 + x1 + x2 + x3, X[2] = x0 − x1 + x2 − x3, and X[1] = (x0 − x2) − j(x1 − x3). For x = [1, 0, −1, 0], X[1] = 2: one cycle of a cosine, amplitude 1, times N/2 = 2.
Common mix-ups
The DFT finds frequencies by guessing.
✓ It is plain multiply-and-add: correlation with fixed probe waves.Sampling faster gives finer frequency resolution.
✓ Resolution is set by the recording length, 1/(N·T).
7.2 Transforms: why engineers change the question
Filtering is a messy running sum in time but a simple multiplication in frequency. What other hard problems become easy when you transform them?
Filtering = multiplying spectra
In time, a filter output is a weighted running sum of the input (a convolution). In frequency, the same operation is just Y(f) = H(f)·X(f): each component is scaled by the gain at its frequency and shifted by the phase. That is why a frequency response is the most useful single description of a filter.
Low-pass, high-pass, and the rest
Low-pass keeps slow changes (smoothing, anti-aliasing). High-pass keeps fast changes and removes offsets and drift (AC coupling, removing gyro bias). A band-pass keeps a range (radio tuning), and a notch removes one frequency (mains hum). High-pass can be built as 1 − low-pass.
The Laplace transform, conceptually
The Fourier transform describes a signal with steady sinusoids. The Laplace transform uses e^{st} with complex s = σ + jω: sinusoids that can also grow or decay. Differentiation becomes multiplication by s, so a circuit's differential equation becomes algebra, e.g. an RC low-pass has H(s) = 1/(1 + sRC). Where H(s) blows up (its poles) tells you whether a system is stable.
Common mix-ups
A transform changes the signal.
✓ It is the same signal described differently; you can always transform back.
Examples to try
Worked solutions are in the interactive chapter online.
The DFT: asking 'how much of this wave?': example 1
Compute all four DFT bins of x = [2, 1, 0, 1].
Transforms: why engineers change the question: example 1
A sensor reading is 2.5 V of steady offset plus a 5 Hz vibration plus 200 Hz noise, sampled at 1 kHz. Which filter keeps just the vibration?
Interactive figures, in words
Figure 7.2 from “The DFT: asking 'how much of this wave?'”
Pick 'cos 2 + ½·sin 3'. Step the probe k from 0 to 7, watching the products column. Which k give big sums, and why do the cosine part and the sine part show up in different columns?
For the signal cos(2·2πn/8) + ½·sin(3·2πn/8), the probe shows |X[k]| = 4 at k = 2 and 6 (cosine part, through the Σx·cos column) and 2 at k = 3 and 5 (sine part, through the Σx·sin column); every other bin is zero.
Figure 7.3 from “Transforms: why engineers change the question”
Compare four filters: moving average and IIR, each as low-pass and high-pass. For each, read the gain at f/fs = 0, 0.05 and 0.45. Write a one-line description of what each would do to a slowly drifting, noisy sensor.
Reading the explorer: both low-pass filters have gain 1 at 0 and small gain near 0.45; both high-pass filters have gain 0 at 0 and close to 1 at high frequencies. On a drifting, noisy sensor the low-pass keeps the drift and removes the noise; the high-pass removes the drift and keeps the noise.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Compute one DFT bin by correlating 100 samples with a test sine and cosine, then check it against a library FFT.
Open online - BUILD: Washing machine, level 3 (BUILD level)
Identify the drum's wobble frequency from its vibration and relate it to the spin speed.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. In an N-point DFT, what does bin k measure?
- The kth sample
- How much the signal matches a wave with k cycles in the window
- The signal's energy up to sample k
- The kth harmonic of the sample rate
Check it in “The DFT: asking 'how much of this wave?'”
2. x = [1, 0, −1, 0]. What is |X[1]| of its 4-point DFT?
Answer:
Check it in “The DFT: asking 'how much of this wave?'”
3. A 1024-point DFT is taken of a signal sampled at 8 kHz. What frequency, in Hz, does bin k = 64 represent?
Answer: Hz
Check it in “The DFT: asking 'how much of this wave?'”
4. You need to tell 100 Hz and 102 Hz apart. What helps most?
- A higher sample rate with the same N
- A longer recording (larger N at the same fs)
- Fewer bits
- Taking the DFT twice
Check it in “The DFT: asking 'how much of this wave?'”
5. Filtering in time corresponds to what in frequency?
- Adding the filter's response
- Multiplying the spectrum by the filter's response
- Dividing by the sample rate
- Nothing simple
Check it in “Transforms: why engineers change the question”
6. Which job needs a high-pass filter?
- Smoothing a jittery thermometer
- Removing a slowly drifting offset from a microphone signal
- Anti-aliasing before an ADC
- Averaging a battery voltage
Check it in “Transforms: why engineers change the question”
7. What does the Laplace transform mainly do for an engineer?
- Speed up sampling
- Turn differential equations into algebra and reveal stability through poles
- Compress audio files
- Replace the DFT in digital filters
Check it in “Transforms: why engineers change the question”
Engineering applications
Tuners and analysers
A guitar tuner records a fraction of a second of sound, takes its spectrum and finds the strongest peak. The recording length sets how finely it can tell two nearby notes apart.
Fast algorithms
Computing a DFT directly takes about N² operations; the fast Fourier transform needs about N log N. That difference is why spectra can be computed in real time on small processors.
Summary
- Each DFT bin correlates the samples with a sinusoid at one frequency.
- Bin k corresponds to k × fs / N hertz; resolution is fs / N.
- Useful bins run up to N / 2, the Nyquist frequency.
- Transforms turn convolution in time into multiplication in frequency, which is why filters are easier to understand there.
Glossary
- Sampling and aliasing
- Sampling measures a signal at regular intervals. Any frequency above half the sample rate, the Nyquist frequency, is indistinguishable from a lower 'alias' frequency.
- Frequency and period
- Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
- Low-pass filter (moving average and EMA)
- A low-pass filter lets slow changes through and attenuates fast ones. In firmware the simplest are the moving average and the exponential moving average.
Project: Find the hidden tones
Generate a signal from two sinusoids 3 Hz apart plus noise, sampled at 200 Hz. Compute its spectrum with recordings of 1 s, 2 s and 4 s, and find the shortest recording that separates the two peaks. Explain the result with the bin spacing.
Deliverables
- Spectra for the three recording lengths
- The shortest length that separates the peaks
- An explanation using fs / N
References
- James W. Cooley and John W. Tukey (1965). "An Algorithm for the Machine Calculation of Complex Fourier Series". Mathematics of Computation 19(90), 297–301.
- Alan V. Oppenheim and Ronald W. Schafer (2010). Discrete-Time Signal Processing, 3rd edition. Pearson.
- Richard G. Lyons (2010). Understanding Digital Signal Processing, 3rd edition. Prentice Hall.
8. Filters seen in frequency
Look at a filter through the frequency lens and its behaviour becomes a single graph: how much of each sinusoid gets through. The moving average passes slow signals, attenuates fast ones and completely blocks certain frequencies, its nulls. The first-order IIR filter, a cousin of the exponential smoother and of the RC circuit, rolls off smoothly above its cut-off. Choosing a filter is choosing that curve.
Figure 8.1. The moving average is a low-pass filter (described in words)
Gain against frequency from 0 to 50 Hz for a 4-point moving average sampled at 100 Hz. The gain is 1 at 0 Hz, 0.769 at 10 Hz, and falls to zero at 25 Hz and 50 Hz, multiples of fs / N.
Explanation
8.1 The moving average, seen in frequency
Averaging the last four readings smooths a sensor beautifully. So why does it completely erase one particular frequency?
One line of code
y[n] = (x[n] + x[n−1] + … + x[n−M+1])/M. It is a finite impulse response (FIR) filter: an impulse affects exactly M outputs, then is forgotten. Random noise of standard deviation σ comes out with σ/√M, because independent errors partly cancel.
Nulls and side lobes
Its gain is 1 at DC and falls to exactly zero at fs/M, 2fs/M, …, with bumps (side lobes) in between: the first is about 0.22 for large M. Great for removing a known interference, like 50 Hz mains when fs/M = 50 Hz, but a mediocre general low-pass because the side lobes leak.
The price: lag
The output is centred (M − 1)/2 samples in the past. With M = 9 at 100 Hz that is 40 ms: fine for a thermometer, dangerous inside a fast control loop where delay erodes stability. Doubling M halves the noise power again but doubles the lag.
Derivation: The moving-average frequency response
Input x[n] = e^{jωn} with ω = 2πf/fs. Output y[n] = (1/M)·Σ_{k=0}^{M−1} e^{jω(n−k)} = e^{jωn}·H, with H = (1/M)·Σ e^{−jωk}.
That is a geometric series: H = (1/M)·(1 − e^{−jωM})/(1 − e^{−jω}).
Factor out half-angles: (1 − e^{−jθ}) = e^{−jθ/2}·2j·sin(θ/2).
So |H| = |sin(ωM/2) / (M·sin(ω/2))| = |sin(πMf/fs)/(M·sin(πf/fs))|, with a pure delay of (M − 1)/2 samples.
It is 1 at f = 0 and 0 whenever Mf/fs is a whole number (other than multiples of M): nulls at f = fs/M, 2fs/M, …
Common mix-ups
A longer moving average is always better.
✓ It smooths more but lags more; inside a control loop the lag can cause oscillation.A moving average blocks all frequencies above its cut-off.
✓ Its side lobes let some high frequencies leak through; it is only zero at the nulls.
8.2 A filter with memory: first-order IIR
One multiply, one add and a single remembered number can smooth a sensor as well as averaging dozens of readings. How?
Infinite memory in one number
Unlike a moving average, the IIR (infinite impulse response) filter feeds its own output back. An impulse never fully disappears; its influence decays by (1 − α) every sample. The weights on past inputs are α, α(1 − α), α(1 − α)², …: an exponentially fading average.
One knob
Large α (close to 1) follows the input almost immediately; small α smooths heavily but responds slowly (time constant about 1/α samples). It behaves like an RC low-pass with RC ≈ T/α, so the cut-off is roughly fc ≈ α·fs/(2π) for small α.
High-pass for free
x[n] − y[n] keeps what the low-pass removed: fast changes pass and any steady offset decays to zero. Use it to remove a slow drift, such as a gyroscope's bias, while keeping quick motions. Combining a high-passed gyro with a low-passed accelerometer is the complementary filter used on drones.
Derivation: Steady state and time constant of the first-order IIR
Filter: y[n] = αx[n] + (1 − α)y[n−1], with 0 < α ≤ 1.
Steady state for constant input X: set y[n] = y[n−1] = y. Then y = αX + (1 − α)y, so αy = αX and *y = X**. DC gain is 1.
Step response from y[−1] = 0: the gap X − y shrinks by (1 − α) each sample, so y[n] = X·(1 − (1 − α)^{n+1}).
Time constant: the gap falls to 1/e (37 %) after n with (1 − α)^n = e^{−1}, so n = −1/ln(1 − α) ≈ 1/α for small α. α = 0.1 gives about 9.5 samples.
Frequency response: H = α/(1 − (1 − α)e^{−jω}). At ω = 0 this is 1; at Nyquist (ω = π) it is α/(2 − α), the strongest attenuation.
Common mix-ups
The IIR filter makes a constant reading smaller.
✓ Its DC gain is 1; constants pass unchanged once it has settled.α is a cut-off frequency.
✓ α is a mixing fraction; the cut-off is roughly α·fs/(2π) for small α.
8.3 The RC time constant, from measurements
A capacitor charging through a resistor never quite finishes. So how can engineers say exactly how long it 'takes'?
Why it slows down
At switch-on the capacitor is empty, so the whole supply voltage sits across the resistor and a big current I = V/R flows. As charge builds up, the capacitor's voltage rises, the resistor's share falls, and the current shrinks. Less current means slower charging. The voltage approaches the supply ever more slowly: it never quite arrives, but it gets close very quickly.
The curve and its landmarks
The charging voltage is v(t) = V(1 − e^(−t/τ)) with τ = R·C. Ohms times farads gives seconds (and kΩ × µF gives milliseconds). After 1τ the capacitor is at 63.2 % of V, after 2τ 86.5 %, after 3τ 95 %, after 5τ 99.3 %. Engineers usually call it 'charged' after about 5τ. Discharging follows v = V·e^(−t/τ): 36.8 % left after one τ.
Measuring τ from data
On a measured curve, the quickest estimate is the time at which the voltage reaches 63 % of its final value. A better one uses every point: rearrange to τ = −t / ln(1 − v/V), compute it at several times and average. If ln(1 − v/V) plotted against t is a straight line, the circuit really is first-order, and the slope is −1/τ. Knowing R, the capacitance follows as C = τ/R.
Hitting a threshold
Many circuits care about when the capacitor crosses a voltage, such as a chip's reset threshold. Solve v = V(1 − e^(−t/τ)) for t: t = −τ·ln(1 − v/V). Crossing half the supply takes τ·ln 2 ≈ 0.69τ; crossing 90 % takes τ·ln 10 ≈ 2.3τ. Thresholds near the supply voltage take much longer and are sensitive to component tolerances.
Derivation: Solving the charging equation
Around the loop: V = i·R + v. The capacitor's current is i = C·dv/dt, so R·C·dv/dt = V − v.
Separate variables: dv/(V − v) = dt/(RC).
Integrate from v = 0 at t = 0: −ln(V − v) + ln V = t/(RC), so ln((V − v)/V) = −t/(RC).
Exponentiate: (V − v)/V = e^(−t/RC), so v(t) = V(1 − e^(−t/τ)) with τ = RC.
At t = τ: v = V(1 − e^(−1)) ≈ 0.632·V. Taking logs of the same line gives the measurement formula τ = −t/ln(1 − v/V).
Common mix-ups
The time constant is how long the capacitor takes to charge fully.
✓ τ is the time to reach about 63 %. 'Fully' (99 %) takes about 5τ, and mathematically it never quite finishes.A bigger supply voltage makes the capacitor charge faster.
✓ τ = RC does not depend on V. A bigger supply reaches any fixed voltage sooner, but the shape and the 63 % time stay the same.The capacitor value printed on the can is exact.
✓ Electrolytic capacitors often have ±20 % tolerance. Measuring τ and dividing by R gives the real value in your circuit.
Examples to try
Worked solutions are in the interactive chapter online.
The moving average, seen in frequency: example 1
A 5-point moving average filters x = [2, 4, 6, 8, 10, 12]. Find y[4] and y[5].
A filter with memory: first-order IIR: example 1
α = 0.2, step input x = 1 from n = 0, y[−1] = 0. Find y[0], y[1], y[2].
The RC time constant, from measurements: example 1
With 9 V, 1 kΩ and 1,000 µF, find τ, the voltage at 0.5 s and 2 s, and the time to reach 5 V.
The RC time constant, from measurements: example 2
A capacitor of unknown value charges from 9 V through 1 kΩ. You measure 6.0 V at 1.1 s. Estimate C.
Interactive figures, in words
Figure 8.2 from “The moving average, seen in frequency”
Choose 'Moving average', low-pass. Set M = 4 and slide the test frequency to find the null. Change M to 8 and 2: where do the nulls go? Watch the step response: how many samples does it take to reach the top?
In the explorer, the 4-point moving average has gain 1 at 0, falls to about 0.77 at f/fs = 0.1, and reaches 0 at f/fs = 0.25 (a null), with a small bump after it. With M = 8 the first null moves to 0.125. The step response climbs in M equal steps to 1.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: RC charging and discharging (Simulation OS experiment)
Measure the RC time constant and compute the cut-off frequency 1 / (2πRC) of the same circuit used as a filter.
Open online - Code Lab (Studio)
Pass sines of 5, 10, 25 and 40 Hz through a 4-point moving average at 100 Hz and measure each output amplitude.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A moving average with M = 10 runs at fs = 500 Hz. What is the lowest frequency it removes completely, in Hz?
Answer: Hz
Check it in “The moving average, seen in frequency”
2. How many samples of delay does a 9-point moving average add?
Answer: samples
Check it in “The moving average, seen in frequency”
3. Noise on a sensor is random with standard deviation 4 mV. Roughly what is it after a 16-point moving average?
- 4 mV
- 1 mV
- 0.25 mV
- 2 mV
Check it in “The moving average, seen in frequency”
4. y[n] = 0.5x[n] + 0.5y[n−1], y[−1] = 0, and x[n] = 4 for n ≥ 0. What is y[1]?
Answer:
Check it in “A filter with memory: first-order IIR”
5. For a constant input X, the first-order IIR low-pass settles at…
- αX
- (1 − α)X
- X
- 0
Check it in “A filter with memory: first-order IIR”
6. Using n ≈ −1/ln(1 − α), about how many samples is the time constant for α = 0.1 (1 decimal place)?
Answer: samples
Check it in “A filter with memory: first-order IIR”
7. A gyroscope reading has a slow, steady bias of 0.3 °/s. Which output removes it?
- The IIR low-pass y
- x − y (the high-pass)
- x itself
- 2y
Check it in “A filter with memory: first-order IIR”
8. After exactly one time constant, how far has a charging capacitor got towards the supply voltage?
- 50 %
- About 63 %
- About 90 %
- 100 %
Check it in “The RC time constant, from measurements”
Engineering applications
Killing mains hum
Averaging over exactly one mains cycle puts a null at the mains frequency and all its harmonics. Precision meters use this to ignore 50 Hz pickup almost completely.
Removing drift
A high-pass filter, built by subtracting a low-pass output from the input, removes slow drift such as a gyroscope's bias, keeping only the fast changes that matter for motion.
Summary
- A filter's frequency response shows the gain applied to each sinusoid.
- An N-point moving average has nulls at multiples of fs / N.
- A first-order IIR filter y = y + α(x − y) behaves like an RC low-pass with time constant τ.
- Input minus low-pass output gives a high-pass filter.
Glossary
- Low-pass filter (moving average and EMA)
- A low-pass filter lets slow changes through and attenuates fast ones. In firmware the simplest are the moving average and the exponential moving average.
- RC time constant
- When a capacitor charges or discharges through a resistor, the voltage changes exponentially with time constant τ = R × C.
- First-order system and time constant
- A first-order system responds to a step by approaching its new value exponentially; its time constant τ is the time to cover 63.2 % of the change.
- Exponential growth and decay
- A quantity decays exponentially when its rate of decrease is proportional to how much is left, giving y = y0 × e^(−t/τ).
Project: A filter to a written spec
A sensor sampled at 200 Hz carries a useful signal below 5 Hz and interference at 50 Hz. Design a moving average and a first-order IIR filter, compute each one's gain at 5 Hz and 50 Hz, and recommend one. Test your recommendation on synthetic data.
Deliverables
- Both designs with their parameters
- Gains at 5 Hz and 50 Hz, calculated and measured
- A recommendation with its lag stated
References
- Alan V. Oppenheim et al. (1997). Signals and Systems, 2nd edition. Prentice Hall.
- Alan V. Oppenheim and Ronald W. Schafer (2010). Discrete-Time Signal Processing, 3rd edition. Pearson.
- Steven W. Smith (1997). The Scientist and Engineer's Guide to Digital Signal Processing. California Technical Publishing.
Known limitations
- Not yet tested by a person using a screen reader; only automated structure checks have run.
- Some interactive lesson diagrams need a pointer or keyboard and a recent browser; their text alternatives carry the same idea without the interaction.
- Mathematics is written as plain text (for example x^2 and sqrt(x)), like the School lessons, not typeset notation.