The same 1 kHz sine can appear as one tall spectral line or as a group of lines. Keep the generator and oscilloscope settings fixed, then choose two lengths from the same capture. Compare a rectangular window with a Hann window to see when a line spreads and how much its tallest bin can understate its amplitude.
A discrete Fourier transform (DFT) compares a record with a grid of sine and cosine frequencies. A fast Fourier transform (FFT) is a way to compute that same transform efficiently. Each grid location is a frequency bin. For N uniformly spaced samples, separated by Δt seconds, the sampling frequency is Fs = 1/Δt and the bin spacing is Δf = Fs/N. The FFT treats the record as one repeat of an N-sample pattern. Its repeat time is NΔt, while the recorded timestamps from the first sample to the last span (N−1)Δt.
A coherent sine completes a whole number of cycles in that repeat time. The repeated pattern then has the same sine phase at its join. A half-integer cycle count puts the sine halfway between two bins. Its endpoints generally fail to join smoothly when the record repeats. Part of the response then appears in nearby and distant bins. This spread is called spectral leakage. The frequency control and sample spacing in this experiment stay fixed. Only the record length used for analysis changes. The unchanged acquisition uses at least 32 samples per input cycle, so this test observes leakage with ample sampling for the single tone.
Before connecting any input or output cables, connect the RIGOL DHO804's rear Ground Terminal to earth ground using the supplied ground cable, as required by the DHO800 User Guide. Its Type-C power input does not ground the instrument through the power cord. Use the supplied power adapter. Keep the AFG1022's protective earth connected. The probe ground clips and any signal cable shields share G0 as described below; they do not replace this required chassis earth lead.
Use the actual exported time step. The synthetic example below uses 160,000 samples per second. A real Memory file can use a different rate. The program checks about 1 kHz input frequency, a small DC offset, sine-fit residual and an evenly spaced time grid. Its two prefixes start at the same first sample. They differ only in the number of rows: round(20Fs/f) and round(20.5Fs/f), where f is estimated independently from rising crossings. Each prefix keeps its retained native rows and their original time intervals.
A window multiplies every retained sample by a known weight before the transform. The rectangular window uses weight 1 throughout. The periodic Hann window uses w[n] = 0.5 − 0.5 cos(2πn/N). It smoothly reduces weights at the beginning and near the end. This usually lowers the distant sidelobes, the smaller responses away from the main peak, while spreading the near response over more bins.
The average of the weights is the coherent gain, equal to 1 for rectangular and 0.5 for periodic Hann. Divide a coefficient by the sum of the weights and double its magnitude to show a one-sided peak voltage at ordinary positive-frequency bins. The zero-frequency bin and, for an even-length record, the Nyquist bin at half the sampling frequency have no separate partner, so they keep the undoubled value. A coherent Hann spectrum shows roughly half the corrected peak in each adjacent bin. The spreading is expected even if the signal was exactly on the center bin.
When the tone sits halfway between two bins, the tallest corrected spectral bin also falls below the fitted time-domain sine amplitude. That shortfall is known as scalloping loss. For an isolated sine in a long record, nearest-bin peak ratios are about 2/π ≈ 0.637 for rectangular and 8/(3π) ≈ 0.849 for Hann. In a finite real-valued record, the mirror spectrum and starting phase can shift the exact largest bin, particularly with the rectangular window. The normalization restores a coherent amplitude. The off-bin shortfall can remain.
For a separate leakage check, the program sums squared FFT magnitudes more than 3.25 bins from the fitted tone and divides by the total windowed spectral energy. It accounts for the mirrored negative-frequency bins. This fraction compares the shape of each window's spectrum. The Hann window also changes the total windowed energy, so the fraction is a within-window normalization. The cutoff leaves both neighboring bins in the near region. It is an experiment definition, not a universal window specification.
The synthetic record uses a 1.000 V peak sine at 1000.000 Hz, sampled at 160 kSa/s. For the 20-cycle prefix, N = 3200 and Δf = 50.000 Hz. The half-bin prefix adds 80 original samples. The 20.000 ms boundary of the first prefix is one 6.25 µs step past its last retained timestamp, 19.99375 ms. N = 3280, Δf ≈ 48.780 Hz and the same 1000 Hz tone sits at bin 20.5. The bin numbers change their frequency spacing with the crop length.
| Prefix | Window | Peak ratio | Far energy (%) |
|---|---|---|---|
| 20 cycles | Rectangular | 1.000 | 0.000 |
| 20 cycles | Hann | 1.000 | 0.000 |
| 20.5 cycles | Rectangular | 0.643 | 6.603 |
| 20.5 cycles | Hann | 0.849 | 0.011 |
The full-record waveform fit subtracts a single DC estimate from both prefixes. The transform uses each prefix's true N. For a length that is not a power of two, Bluestein's algorithm computes the native DFT using an internal padded convolution. The reported bins still use Fs/N. Extra computational workspace does not add information to the measured record.
If both windows show many distant bins, check the original waveform for clipping, distortion, coupling or noise. If the sample spacing check fails, use a new native Memory export instead of retiming the CSV. The analyzer deliberately leaves irregularly sampled or noisy captures unresolved. The example is synthetic. The actual generator, scope and bench have yet to be measured.
Use Python 3.9 or later and the standard library. Download the complete program, tests, template, editable schematic and example. Exit 0 means the controlled comparison passed. Exit 1 means unresolved data and 2 indicates malformed input or command syntax.
python3 fft_windows.py capture.csv
python3 fft_windows.py synthetic/input.csv
python3 -m unittest -v test_fft_windows
"""Compare rectangular and periodic Hann FFTs of two native prefixes of one sine."""
import argparse
import cmath
import csv
import math
from dataclasses import dataclass
from pathlib import Path
HEADER = ("time_s", "voltage_v")
MAX_BYTES, MAX_ROWS = 1_400_000, 18_000
class BadInput(ValueError):
pass
class Unresolved(ValueError):
pass
@dataclass(frozen=True)
class Spectrum:
amplitude: tuple
peak_ratio: float
far_fraction: float
def bounded(value, low, high, label):
if not low - 1e-9 <= value <= high + 1e-9:
raise Unresolved(f"{label} is {value:.6g}; expected {low:g} to {high:g}")
return value
def read_capture(path):
try:
if path.stat().st_size > MAX_BYTES:
raise BadInput("file exceeds byte limit")
with path.open(newline="", encoding="utf-8-sig") as file:
reader = csv.reader(file, strict=True)
if tuple(next(reader, ())) != HEADER:
raise BadInput("header must be " + ",".join(HEADER))
rows = []
for line, row in enumerate(reader, 2):
if line > MAX_ROWS + 1:
raise BadInput("record exceeds row limit")
if len(row) != 2:
raise BadInput(f"row {line}: expected two columns")
try:
time, voltage = map(float, row)
except ValueError as error:
raise BadInput(f"row {line}: expected numeric values") from error
if not (math.isfinite(time) and math.isfinite(voltage)):
raise BadInput(f"row {line}: values must be finite")
if rows and time <= rows[-1][0]:
raise BadInput(f"row {line}: time must be strictly increasing")
rows.append((time, voltage))
except (OSError, UnicodeError, csv.Error) as error:
raise BadInput(str(error)) from error
if len(rows) < 64:
raise Unresolved("too few samples")
return zip(*rows)
def radix_two(values, inverse=False):
n = len(values)
data = list(values)
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j ^= bit
if i < j:
data[i], data[j] = data[j], data[i]
span = 2
while span <= n:
half = span // 2
direction = 1 if inverse else -1
twiddle = [cmath.exp(2j * math.pi * direction * k / span) for k in range(half)]
for offset in range(0, n, span):
for k, phase in enumerate(twiddle):
i, j = offset + k, offset + k + half
term = phase * data[j]
data[i], data[j] = data[i] + term, data[i] - term
span *= 2
return [value / n for value in data] if inverse else data
def fft(values):
"""Forward DFT with its native N grid, using radix-2 or a chirp convolution."""
n = len(values)
if n < 1:
raise ValueError("FFT requires at least one sample")
if (n & (n - 1)) == 0:
return radix_two(values)
# Bluestein computes the native DFT through a linear chirp convolution.
padded = 1 << (2 * n - 2).bit_length()
chirp = [cmath.exp(-1j * math.pi * ((k*k) % (2*n)) / n) for k in range(n)]
left, right = [0j] * padded, [0j] * padded
right[0] = 1
for k in range(n):
left[k] = values[k] * chirp[k]
if k:
right[k] = right[-k] = chirp[k].conjugate()
convolution = radix_two([a*b for a, b in zip(radix_two(left), radix_two(right))],
inverse=True)
return [chirp[k] * convolution[k] for k in range(n)]
def centered_fit(times, values, frequency):
cosines = [math.cos(2*math.pi*frequency*t) for t in times]
sines = [math.sin(2*math.pi*frequency*t) for t in times]
cols = [[1.0]*len(times), cosines, sines]
matrix = [
[sum(a*b for a,b in zip(left,right)) for right in cols] +
[sum(a*v for a,v in zip(left,values))]
for left in cols
]
for i in range(3):
pivot = max(range(i,3), key=lambda j: abs(matrix[j][i]))
matrix[i], matrix[pivot] = matrix[pivot], matrix[i]
number = matrix[i][i]
if abs(number) < 1e-8:
raise Unresolved("cannot fit the sine with these timestamps")
matrix[i] = [value/number for value in matrix[i]]
for j in range(3):
if j != i:
factor = matrix[j][i]
matrix[j] = [r-factor*p for r,p in zip(matrix[j],matrix[i])]
dc, cosine, sine = (row[-1] for row in matrix)
peak = math.hypot(cosine,sine)
rms = math.sqrt(sum(
(v-dc-cosine*c-sine*s)**2 for v,c,s in zip(values,cosines,sines)
) / len(values))
return dc, peak, rms
def characterize(times, volts):
if any(abs(t)>1 for t in times):
raise Unresolved("shift the time origin by one constant to within ±1 s")
times = [t-times[0] for t in times]
n = len(times)
span = times[-1]
bounded(span, .023, .100, "input periods at nominal 1 kHz (record span in s)")
dt = span/(n-1)
gaps = [b-a for a,b in zip(times,times[1:])]
bounded(max(abs(gap/dt-1) for gap in gaps), 0, .001, "sample spacing variation")
bounded(max(abs(t-i*dt)/dt for i,t in enumerate(times)), 0, .025, "sample grid deviation")
bounded(min(volts), -1.35, 1.35, "raw voltage minimum")
bounded(max(volts), -1.35, 1.35, "raw voltage maximum")
center = (min(volts)+max(volts))/2
crossings = [
t0 + (t1-t0)*(center-v0)/(v1-v0)
for t0,t1,v0,v1 in zip(times,times[1:],volts,volts[1:])
if v0 < center <= v1
]
if len(crossings) < 22:
raise Unresolved("input periods: need 22 rising crossings")
period = (crossings[-1]-crossings[0])/(len(crossings)-1)
frequency = 1/period
bounded(frequency, 995, 1005, "sine frequency (Hz)")
bounded(max(abs((b-a)/period-1) for a,b in zip(crossings,crossings[1:])),
0, .005, "input period variation")
bounded(period/dt, 32, 2000, "samples per cycle")
dc, peak, residual = centered_fit(times, volts, frequency)
bounded(dc, -.060, .060, "DC center (V)")
bounded(peak, .86, 1.14, "sine peak (V)")
bounded(residual/peak, 0, .018, "sine-fit residual relative to peak")
return 1/dt, frequency, peak, [v-dc for v in volts]
def spectrum(values, ratio, peak, use_hann):
n = len(values)
weights = ([.5-.5*math.cos(2*math.pi*i/n) for i in range(n)]
if use_hann else [1.0] * n)
normalizer = sum(weights)
transform = fft([v*w for v,w in zip(values,weights)])[:n//2+1]
power, amplitude = [], []
for k,value in enumerate(transform):
# Pair positive and negative frequencies, except DC and even-length Nyquist.
factor = 1 if k == 0 or 2 * k == n else 2
amplitude.append(factor*abs(value)/normalizer)
power.append(factor*abs(value)**2)
local = [a for k,a in enumerate(amplitude) if abs(k-ratio) <= 1]
far = sum(p for k,p in enumerate(power) if abs(k-ratio)>3.25)
return Spectrum(tuple(amplitude), max(local)/peak, far/sum(power))
def compare(values, sample_rate, frequency, peak):
cases = []
for cycles, label in ((20, "near integer"), (20.5, "near half-bin")):
n = round(cycles*sample_rate/frequency)
if n > len(values):
raise Unresolved("capture too short for both prefixes")
actual = n*frequency/sample_rate
bounded(abs(actual-cycles), 0, .018, label+" bin placement")
rect = spectrum(values[:n], actual, peak, False)
hann = spectrum(values[:n], actual, peak, True)
cases.append((label,n,actual,rect,hann))
_,_,_,cr,ch = cases[0]
_,_,_,hr,hh = cases[1]
bounded(cr.peak_ratio,.970,1.030,"near-integer rectangular peak ratio")
bounded(ch.peak_ratio,.970,1.030,"near-integer Hann peak ratio")
for result,lower,upper,name in ((cr,0,.045,"rectangular"),(ch,.46,.54,"Hann")):
adjacent = max(result.amplitude[19],result.amplitude[21])/peak
bounded(adjacent,lower,upper,"near-integer "+name+" adjacent bin")
bounded(hr.peak_ratio,.60,.68,"half-bin rectangular peak ratio")
bounded(hh.peak_ratio,.82,.88,"half-bin Hann peak ratio")
if hr.far_fraction < .025 or hh.far_fraction > .004 or hr.far_fraction < 8*hh.far_fraction:
raise Unresolved("far-bin comparison is not resolved by this capture")
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("capture",type=Path,help="one native uniformly sampled sine capture")
args = parser.parse_args()
try:
times, volts = read_capture(args.capture)
sample_rate,frequency,peak,values = characterize(times,volts)
cases = compare(values,sample_rate,frequency,peak)
except BadInput as error:
parser.exit(2,f"INPUT: {error}\n")
except Unresolved as error:
parser.exit(1,f"UNRESOLVED: {error}\n")
print(f"full record: Fs {sample_rate:.1f} Hz, sine {frequency:.3f} Hz, {peak:.3f} V peak")
for label,n,actual,rect,hann in cases:
print(f"{label}: N={n}, bin spacing {sample_rate/n:.3f} Hz, tone at bin {actual:.4f}")
for name,info in (("rectangular",rect),("Hann",hann)):
near = " ".join(f"{a/peak:.3f}" for a in info.amplitude[19:23])
print(f" {name:11} | peak/time-domain {info.peak_ratio:.3f} | "
f"far energy {100*info.far_fraction:.3f}% | bins 19–22: {near}")
print("PASS: Hann gave less far leakage in the half-bin comparison.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
The input remains a coherent 1 V peak sine. It fills exactly 20 cycles, and bins 19 and 21 each show about 0.5 V after applying a periodic Hann window. Do the adjacent bins establish two extra input tones?
The adjacent responses come from weighting the coherent sine with the Hann window. In this example, the rectangular reading returns almost all the response to bin 20. The two windows reveal the same input tone with different spectral shapes.