Sampling and aliasing: filter before throwing samples away
采样与混叠
Derive frequency folding and its phase boundary, then measure a finite low-pass filter before factor-two downsampling.
sampling-aliasingHow can 6,500Hz become 1,500Hz?
Generate two zero-phase cosines at a sample rate of 8,000 Hz: one at 6,500 Hz and one at 1,500 Hz. Their aligned sample arrays agree within floating-point error. A program receiving only those numbers cannot tell which continuous signal produced them. Different continuous signals producing identical samples is aliasing. Indistinguishability under sampling
This is more specific than “poor audio quality”: the measurement has already made alternatives indistinguishable. A larger model or a higher sample-rate label cannot make the same numbers uniquely identify the original high frequency. Avoiding aliasing requires restricting bandwidth before discarding time information.
We first derive frequency folding from equal samples, then perform digital downsampling. Keep two settings separate: analog sound needs analog anti-alias processing before an analog-to-digital converter (ADC); correctly sampled digital audio needs digital low-pass filtering before reducing its sample rate. The latter program cannot retrospectively fix aliasing that already occurred in the former.
Which differences does uniform sampling hide?
Let be the sample rate, a continuous frequency and an integer sample index. Complex exponentials separated by an integer multiple of the sample rate agree at every sampling instant:
A real zero-phase cosine also cannot distinguish positive from negative frequency. Its frequency folded into is therefore:
The remainder is in . At 8 kHz, 6.5 kHz is first equivalent to −1.5 kHz, then corresponds to 1.5 kHz by cosine symmetry. Phase still matters: a 6.5 kHz component with phase requires phase on the 1.5 kHz branch, not the unchanged phase.
Ideal sampling results require assumptions such as strict band limitation to , ideal uniform sampling and sufficiently complete sample information. They do not say that joining an arbitrary finite set of points with straight lines recovers the original. The DSP Guide explains folding near half the sample rate; we additionally check the equality boundary through phase. Conditions of sampling results
A sine exactly at can disappear entirely while a cosine remains. The equality boundary is not an unconditional guarantee for arbitrary phase. Real filters also require transition bands; a target maximum frequency cannot simply imply an ideal sample rate without any margin.
Downsampling by two keeps even-indexed samples and makes the rate . A 3 kHz component in an 8 kHz recording now lies above the new 2 kHz Nyquist frequency and folds to 1 kHz. Low-pass filtering must precede selection of even samples to suppress this incoming contamination. SciPy’s resample_poly documentation describes rate expansion, low-pass filtering and extraction; here we implement only a small integer factor-two reduction. Filtering order in resampling
Let be an odd tap count, its center and the cutoff. Multiply the ideal low-pass sinc response by a Hamming window and normalize its DC gain to construct a finite impulse response (FIR) filter:
Here , with continuous limit 1 at zero. Finite truncation prevents an ideal rectangular response. For centered convolution of a periodic signal, the frequency response directly predicts each sinusoid’s amplitude change:
This provides an independent check: compare the filter response with signal projection rather than accepting a waveform because it “looks smooth.”
Choose frequencies that can be checked by hand
The complete program uses Python 3.12 and NumPy 1.26.4. Its synthetic signal contains 256 samples at 8 kHz: a 500 Hz cosine of amplitude 1 and a 3 kHz cosine of amplitude 0.6. Both complete integer cycles within the recording, preventing nonalignment leakage from confounding projection.
"""Sampling identities and a finite low-pass filter before decimation by two.
The FIR demonstration uses periodic convolution and bin-aligned synthetic tones.
It is not an analog anti-alias filter or a general-purpose resampler.
"""
import json
import numpy as np
def tone(frequency,rate=8000,count=256,phase=0.):
if type(rate) is not int or not 1<=rate<=48000 or type(count) is not int or not 2<=count<=4096:raise ValueError('Invalid bounded sample grid')
if not np.isfinite([frequency,phase]).all() or abs(frequency)>8*rate or abs(phase)>100:raise ValueError('Invalid frequency or phase')
return np.cos(2*np.pi*frequency*np.arange(count)/rate+phase)
def folded_frequency(frequency,rate):
if not np.isfinite([frequency,rate]).all() or rate<=0 or abs(frequency)>8*rate:raise ValueError('Invalid alias frequency')
return float(abs((frequency+rate/2)%rate-rate/2))
def lowpass(cutoff,rate=8000,taps=63):
if type(taps) is not int or not 3<=taps<=255 or taps%2!=1 or not np.isfinite([cutoff,rate]).all() or not 0<cutoff<rate/2:raise ValueError('Use an odd filter and cutoff below Nyquist')
n=np.arange(taps)-(taps-1)/2;h=(2*cutoff/rate)*np.sinc(2*cutoff*n/rate)*np.hamming(taps)
return h/h.sum()
def periodic_filter(x,h):
if np.iscomplexobj(x) or np.iscomplexobj(h):raise ValueError('Real data and kernel required')
x=np.asarray(x,dtype=float);h=np.asarray(h,dtype=float)
if x.ndim!=1 or h.ndim!=1 or not 2<=len(x)<=4096 or not 1<=len(h)<=255 or len(h)%2!=1 or not np.isfinite(x).all() or not np.isfinite(h).all() or np.max(abs(x))>8 or np.max(abs(h))>2:raise ValueError('Use finite one-dimensional data and an odd kernel')
center=len(h)//2
return sum(weight*np.roll(x,i-center) for i,weight in enumerate(h))
def amplitude(x,frequency,rate):
if np.iscomplexobj(x):raise ValueError('Real samples required')
x=np.asarray(x,dtype=float)
if x.ndim!=1 or not 2<=len(x)<=4096 or not np.isfinite(x).all() or np.max(abs(x))>8 or not 0<frequency<rate/2:raise ValueError('Use a finite signal and interior frequency')
cycles=frequency*len(x)/rate
if not np.isclose(cycles,round(cycles),rtol=0,atol=1e-10):raise ValueError('Projection requires a bin-aligned tone')
return float(2*abs(np.dot(x,np.exp(-2j*np.pi*frequency*np.arange(len(x))/rate)))/len(x))
def demo():
rate=8000;count=256;low=tone(500,rate,count);high=.6*tone(3000,rate,count);x=low+high;h=lowpass(1500,rate)
raw=x[::2];filtered=periodic_filter(x,h)[::2]
return dict(rate=rate,decimated_rate=4000,original=x.tolist(),raw=raw.tolist(),filtered=filtered.tolist(),filter=h.tolist(),
alias=dict(high=6500,low=1500,max_sample_difference=float(np.max(abs(tone(6500)-tone(1500))))),
nyquist=dict(cosine=tone(4000,count=8).tolist(),sine=tone(4000,count=8,phase=-np.pi/2).tolist()),
amplitudes={label:{str(f):amplitude(y,f,4000) for f in [500,1000]} for label,y in [('raw',raw),('filtered',filtered)]},
filter_dc_gain=float(h.sum()),filter_delay_samples=31,
scope='Centered periodic convolution removes the displayed delay; a causal implementation has group delay 31 input samples.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
Direct selection of even samples produces 128 samples at 4 kHz. Projected amplitudes are approximately 1 at 500 Hz and 0.6 at 1 kHz. Filtering first with 63 taps and a 1.5 kHz cutoff gives approximately 0.9998770395 at 500 Hz and a 0.000399992 residual at 1 kHz. The filter suppresses folded contamination, but neither preserves the passband exactly nor makes the stopband identically zero.
periodic_filter joins the record’s ends and centers the filter. A real causal implementation of the same symmetric FIR has a group delay of 31 input samples, or 3.875 ms. Centering removes displayed delay here; it does not establish a zero-latency streaming system. SciPy’s documentation separately discusses boundary padding and symmetric odd-length filters. Our periodic boundary is different from its default zero padding. Boundary and phase conventions
amplitude accepts only interior frequencies aligned to integer cycles in the record. DC and Nyquist cannot use the same doubled-amplitude factor mechanically. Bounds are 4,096 input samples and 255 filter taps. Direct convolution takes time, rolled arrays use temporary space, and single-frequency projection takes . This is not a general rational-rate or polyphase resampler.
Filtering helps before information disappears
If an ADC has already folded 6.5 kHz into 1.5 kHz, subsequent digital low-pass filtering to 2 kHz retains both that contamination and a genuine 1.5 kHz signal: their digital representations agree. Filtering before digital downsampling works because the old sample rate still preserves their distinction.
Filter selection needs passband, transition band, stopband attenuation, delay and boundary policies. More taps generally offer more freedom to shape a response while increasing direct computation and delay costs. One fixed cutoff and tap count cannot be best for every recording. Our aligned periodic cosines do not test nonperiodic boundaries, clock jitter or actual hardware noise. For spectra and projection, see the Fourier transform.
Predict the fold before running the program
-
Understanding. Can samples distinguish zero-phase cosines at 6.5 kHz and 1.5 kHz when sampled at 8 kHz?
Answer: No. The first is equivalent to −1.5 kHz, and a zero-phase real cosine is symmetric in frequency sign. With nonzero phase, the folded low-frequency phase must reverse sign.
-
Calculation. An 8 kHz signal contains a 3 kHz cosine of amplitude 0.6. What frequency and amplitude appear after direct factor-two downsampling?
Answer: The new rate is 4 kHz, so 3 kHz folds to 1 kHz with amplitude still 0.6. Extraction does not first attenuate it. Only with filtering is the residual determined by .
-
Counterexample. Why does “at least twice the maximum frequency” fail to guarantee recovery of arbitrary sinusoidal phase at equality?
Answer: The Nyquist sine is zero at every sample and cannot be distinguished from the absence of that component; alternates between ±1. General recovery needs explicit conditions such as strict band limitation.
-
Transfer. Can a streaming system using a 63-tap symmetric causal FIR adopt this example’s centered, undisplayed delay?
Answer: No. The causal filter has a 31-input-sample group delay: 3.875 ms at 8 kHz. It also needs state and boundary handling. Centered periodic processing has access to surrounding samples under different timing conditions.
Separate the theorem, library workflow and original example
DSP Guide chapter 3 discusses quantization, sampling and frequency folding. Independent algebra supplies the Nyquist phase check and our filter-response calculation. SciPy 1.15.3 documentation checks the order of low-pass filtering and extraction, plus boundary and phase choices. We neither ran the library nor reproduced its entire polyphase path. All numerical results use finite synthetic signals.
Make a prediction, then check
When must the digital low-pass run for factor-two downsampling?
Learning objectives
- Derive aliases from equal discrete samples.
- Explain the Nyquist phase counterexample.
- Measure passband and folded residual amplitudes.
- Separate digital decimation from already aliased ADC input.
Prerequisites & connections
Explore related knowledge →References
- The Scientist and Engineer’s Guide to DSP, chapter 3: ADC and DAC
Steven W. Smith - SciPy 1.15.3: scipy.signal.resample_poly
SciPy contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked complex-exponential sample equivalence, real-frequency folding with reflected phase, Nyquist sine/cosine boundary, finite Hamming-sinc FIR and frequency-response predictions against scoped DSP Guide3 and SciPy1.15.3 resampling documentation. Six paired equations and four explained exercises. Periodic centered factor-two example is not a full polyphase or real ADC implementation.
- Checked6500/1500Hz identical samples, phase reversal, lost Nyquist sine, normalized symmetric63-tap filter, frequency-response predicted residual and causal3.875ms delay.
- Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- The Scientist and Engineer’s Guide to DSP, chapter 3: ADC and DAC · Read Quantization and Sampling Theorem sections; visually inspected printed page40. Half-step error needs no saturation; the Nyquist equality/phase counterexample is independently derived. Current PDF revision year not verified.
- SciPy 1.15.3: scipy.signal.resample_poly · Read algorithm introduction, padding and symmetric odd-filter phase guidance. Our centered periodic factor-two FIR example does not replicate the complete rational polyphase implementation or its default boundaries.
Related topics