Signals and frequency · constructed experiment
Beat Envelope and Spectral Lines Are Different Things
Two nearby tones can produce a slow rise and fall while the original signal still contains only the two input frequencies. Calculate the waveform and its spectrum, then square it to see exactly where a new difference-frequency line comes from.
Verification scope: All traces and tables are calculated from explicit real-number formulas. They are not microphone, oscilloscope or circuit measurements. The full Python program and behavior tests run on a normal computer are included; no sound output, target firmware build, target execution or physical test is claimed.
Two tones, one changing outline
A signal is a quantity represented as a function of time. Here it has arbitrary amplitude units, so it does not imply a voltage, pressure or power. A sinusoid is a smooth periodic oscillation described by sine or cosine. Its frequency counts complete cycles each second, measured in hertz (Hz). Its amplitude is the size of its excursion from zero. Its phase specifies where within a cycle the oscillation starts; the code expresses phase in radians, with 2π radians making one complete turn.
Construct two cosine signals with equal peak amplitude one, zero initial phase and frequencies f₁ = 100 Hz and f₂ = 104 Hz. Add them point by point. Addition is a linear operation: scaling and adding inputs scales and adds the corresponding output. Their combined signal is
x(t) = cos(2π100t) + cos(2π104t) = 2 cos(2π2t) cos(2π102t).
The equality follows from the cosine sum-to-product identity. The arithmetic mean frequency is 102 Hz and the difference is Δf = 4 Hz. The product expression groups the same waveform into a fast cosine and a slow signed multiplier. It does not say that a separate 102 Hz or 2 Hz sinusoid has been added to the original sum.
An envelope describes the changing outline or local amplitude of an oscillation. Specify which convention you mean. The signed factor 2 cos(2π2t) is a 2 Hz cosine: after half its period, its sign reverses. The nonnegative magnitude envelope E(t) = 2|cos(2π2t)| has maxima four times each second, because taking the absolute value folds negative lobes upward. The usual audible beat repetition for these equal positive-frequency tones is |f₂ − f₁| = 4 Hz. The two statements are consistent.

What counts as a spectral line?
A spectrum describes a signal through its frequency components. A spectral line is a component concentrated at one exact frequency in an ideal indefinitely lasting periodic signal. For the original sum, the positive-frequency lines are at 100 and 104 Hz, with peak amplitude one each. There is no added line at 2, 4 or 102 Hz. A changing outline and an added low-frequency signal are different properties.
One way to verify this is to expand the product expression back into a sum: multiplying the 102 Hz cosine by the 2 Hz factor produces the two side frequencies 102 − 2 and 102 + 2. A sideband is a component offset from a reference frequency by a modulation frequency. Here that language is a way of describing the original two components. It does not create a carrier line at 102 Hz. A carrier is a reference fast oscillation used when describing modulation; a suppressed carrier may have no spectral line of its own.
Real cosine signals also require negative frequencies in a two-sided complex representation, which combines real and imaginary numbers. The mathematical identity cos(2πft) = [exp(i2πft) + exp(−i2πft)]/2 pairs +f with −f; i is the imaginary unit, whose square is −1, and exp denotes the exponential function. Each two-sided line has magnitude one-half for a unit real cosine. Negative frequency labels the opposite direction of complex phase rotation. It does not mean a real loudspeaker must oscillate backward in time. With zero phase, cos(−2πft) equals cos(2πft).
The delivered plots use a one-sided peak-amplitude spectrum: the pair of nonzero positive and negative components is represented by one positive-frequency peak of amplitude one. The zero-frequency component and the special sampling-limit endpoint are not doubled. These values are amplitudes, not power, and not a density per hertz.
Squaring creates a difference component
Squaring means multiplying the signal by itself. It is nonlinear: the square of a sum includes cross terms. An ideal square-law detector is a device or mathematical operation whose output is proportional to the input squared. In this experiment the operation is simply Python multiplication, without any claim about a physical detector’s response.
x²(t) = 1 + cos(2π4t) + ½cos(2π200t) + cos(2π204t) + ½cos(2π208t).
The new 4 Hz component appears in the squared signal, together with a constant value one and higher-frequency terms. The constant is the direct-current (DC) component, meaning the zero-frequency average; the name is used for signal averages even when no electrical current is involved. The difference line belongs to the nonlinear output. It was not an extra component hiding in the original linear sum.
If an ideal low-pass filter, which passes lower frequencies and suppresses higher ones, removes the 200 Hz and higher terms while retaining 4 Hz, its output is 1 + cos(2π4t). Equivalently, averaging over the fast 102 Hz cycles while retaining slow variation gives E²(t)/2 = 1 + cos(2π4t). This is an ideal separation of timescales, not the same as taking the instantaneous square or an average across the entire record. The program delivers the unfiltered square so the distinction stays visible.
In a physical wave experiment, an intensity or average power may be proportional to squared amplitude under stated medium, impedance and detector conditions. Those proportionality factors and response times are absent from this dimensionless model. Labeling x² “measured intensity” would add unsupported physics. We call it a squared signal and report its units as arbitrary units squared.

A sampled record needs controlled duration and window
Sampling stores the signal at separate equally spaced times. The sample rate fₛ is the number of samples per second. A record of N samples uses tₙ = n/fₛ for n = 0 through N − 1. Its analysis duration is T = N/fₛ, even though the last stored sample lies at (N − 1)/fₛ. Our baseline is fₛ = 1024 samples per second, N = 1024 and T = 1 second.
The discrete Fourier transform (DFT) compares a finite sampled record with oscillations at discrete frequencies. A bin is one of those frequency positions, kfₛ/N. Here bin spacing is Δfbin = fₛ/N = 1 Hz, so both tones fit exact bins. The program uses the direct sum X[k] = Σ x[n]w[n] exp(−i2πkn/N), calculating its real and imaginary parts with sine and cosine. It is deliberately transparent and slower than a fast Fourier transform, a faster algorithm for the same transform. No numerical package is required.
A window is the set of weights w[n] applied before the transform. A rectangular window gives every stored sample weight one. A periodic Hann window tapers the record using w[n] = ½ − ½cos(2πn/N), for n from 0 through N − 1. The word “periodic” matters: the symmetric form used in some filter design has N − 1 in its denominator. We use the periodic form for spectral analysis.
A tone is coherent with a record when it completes an integer number of cycles in the analysis duration. Our 100 and 104 Hz baseline tones are coherent with the one-second record. With the rectangular window their energy occupies their exact bins, apart from floating-point rounding, the small error from representing calculations with finite numerical precision. A Hann window deliberately broadens even a coherent isolated line into neighboring bins. Those neighbors are the window’s response, not new physical tones.
Spectral leakage is spreading across bins when the finite record and its window do not isolate a component to one bin. Change only f₂ to 104.5 Hz and keep N = 1024. The half-bin offset produces leakage. Hann weighting reduces distant leakage but broadens the central response. The program divides transform magnitudes by the sum of the weights and doubles only the interior positive bins. That corrects an isolated coherent sinusoid’s peak amplitude; it does not make every off-bin peak an exact amplitude estimate, separate overlapping tones automatically, or remove leakage.
| Constructed control | Duration / bin spacing | What it tests |
|---|---|---|
| 100 + 104 Hz, 1024 samples, rectangular | 1 s / 1 Hz | Two raw peaks of one; no raw 4 Hz component |
| Same tones and record, periodic Hann | 1 s / 1 Hz | Corrected isolated peak and neighboring window bins |
| 100 + 104.5 Hz, both windows | 1 s / 1 Hz | Off-bin leakage and distant-leakage reduction |
| 100 + 104 Hz, 128 samples | 0.125 s / 8 Hz | Short record cannot separate these tones cleanly |
| 100 + 104 Hz, amplitudes 1 and 0.4 | 1 s / 1 Hz | Envelope minimum stays above zero at 0.6 |
The Nyquist frequency is half the sample rate, the boundary beyond which distinct continuous tones can produce indistinguishable sampled sequences. That confusion is aliasing. The generator rejects input tones at or outside ±fₛ/2 rather than silently pretending they are uniquely represented. With the defaults, even the largest squared component, 208 Hz, is below 512 Hz. Changing the input tones can make squaring produce components above that limit; the summary reports whether the squared components stay below it. A valid raw record does not guarantee an unaliased nonlinear output.
Unequal amplitudes, phase and signed frequencies
For nearby positive tones with amplitudes A₁ and A₂ and relative phase φ, the phasor-magnitude envelope satisfies
E²(t) = A₁² + A₂² + 2A₁A₂ cos[2π(f₂ − f₁)t + φ].
A phasor is a rotating complex vector used to represent amplitude and phase. The code adds the two vectors and takes their magnitude, avoiding numerical cancellation from subtracting nearly equal squared quantities. Equal amplitudes can cancel fully; amplitudes 1 and 0.4 give a minimum 0.6 and a maximum 1.4. A relative phase of π moves equal-tone cancellation to t = 0.
The program also accepts negative signed frequencies as a mathematical control. For zero phase, replacing +100 Hz with −100 Hz leaves the real cosine samples unchanged. But a magnitude calculated by adding the originally specified signed rotating vectors is not generally the slowly varying envelope of that real waveform. The trace therefore names that column phasor_magnitude_au, and the envelope interpretation in this article is restricted to nearby positive-frequency tones. This avoids treating a sign convention as another measured beat.
Run and compare the records
Use Python 3.9 or later on a computer; the recorded run on the author’s computer used Python 3.9.6. The only components are the complete beats.py program and its test_beats.py suite. No circuit connections or electronics board is needed. The supplied ZIP compressed reader archive includes the complete article, original figures, code and blank observations. See the reader contents and reproduction instructions. Figure originals use Scalable Vector Graphics (SVG), editable shapes and labels; pixel-based copies use Portable Network Graphics (PNG). The standalone reader uses Hypertext Markup Language (HTML) and Cascading Style Sheets (CSS). Its data use comma-separated values (CSV), and the summary uses JavaScript Object Notation (JSON), a structured text format for named values.
Extract the archive, keep the folder structure and open standalone-preview.html. Then use a terminal’s command-line interface (CLI), the text prompt for running programs, from the extracted folder:
python3 -m unittest discover -s code -v
python3 code/beats.py --out-dir my-coherent
python3 code/beats.py --window hann --out-dir my-hann
python3 code/beats.py --f2 104.5 --out-dir my-offbin-rect
python3 code/beats.py --f2 104.5 --window hann --out-dir my-offbin-hann
python3 code/beats.py --samples 128 --out-dir my-short
python3 code/beats.py --amplitude2 0.4 --out-dir my-unequal
- First inspect each
summary.json: confirm the intended frequencies, count, sample rate, duration and window. A repeated old file is not evidence of a changed run. - Plot
trace.csvas raw signal against time. Compare its changing outline withphasor_magnitude_auusing the baseline positive tones. - Read
spectrum.csvat 2, 4, 100, 102 and 104 Hz. The first two and the midpoint should be close to numerical zero in the baseline; 100 and 104 should be one. - Read
squared-spectrum.csvat 0, 4, 200, 204 and 208 Hz and compare the exact expansion above. Keep the amplitude units separate from the raw spectrum. - Change one control at a time. Compare distant bins for off-bin leakage, and record the broadening as well as the reduction. Use
data/blank-observations.csvto keep expected and observed computational results separate.
Complete executable model
The direct transform performs work proportional to N squared. Use the supplied record sizes for a quick experiment; very large counts will take longer. Bad numeric inputs and invalid sample counts produce clear errors. The output directory contains newly calculated records, not acquired measurements.
#!/usr/bin/env python3
"""Construct two real tones and calculate spectra, using only standard Python."""
import argparse
import csv
import json
import math
from pathlib import Path
def finite(value, name):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ValueError(name + ' must be a finite real number')
return value
def tone_sum(t, f1, f2, a1=1.0, a2=1.0, phase2=0.0):
"""Two real cosines, first phase zero, second phase in radians."""
for name, value in [('t', t), ('f1', f1), ('f2', f2), ('a1', a1), ('a2', a2), ('phase2', phase2)]:
finite(value, name)
if a1 < 0 or a2 < 0:
raise ValueError('amplitudes must be nonnegative; use phase for inversion')
return a1 * math.cos(2 * math.pi * f1 * t) + a2 * math.cos(2 * math.pi * f2 * t + phase2)
def envelope(t, f1, f2, a1=1.0, a2=1.0, phase2=0.0):
"""Magnitude of the two phasors; equal positive tones give 2|cos(pi*df*t)|.
This is a useful slow envelope when positive frequencies are nearby.
Signed-frequency inputs remain mathematical phasors, not a claim of a
slowly varying real-signal envelope for every possible signed pair.
"""
# Use vector magnitude rather than subtraction of nearly equal squares.
tone_sum(t, f1, f2, a1, a2, phase2) # Shared input checks.
phase = 2 * math.pi * (f2 - f1) * t + phase2
return math.hypot(a1 + a2 * math.cos(phase), a2 * math.sin(phase))
def make_trace(fs, n, f1, f2, a1=1.0, a2=1.0, phase2=0.0):
finite(fs, 'sample rate')
if fs <= 0:
raise ValueError('sample rate must be positive')
if type(n) is not int or n < 4 or n % 2:
raise ValueError('sample count must be an even integer >= 4')
tone_sum(0, f1, f2, a1, a2, phase2)
if abs(f1) >= fs / 2 or abs(f2) >= fs / 2:
raise ValueError('each tone must be strictly inside +/- sample_rate/2')
return [tone_sum(i / fs, f1, f2, a1, a2, phase2) for i in range(n)]
def amplitudes(values, fs, window='rect'):
"""One-sided peak-amplitude DFT; not power or power spectral density.
Divide by sum(window), double interior positive-frequency bins only.
Hann correction is for isolated on-bin tones, not arbitrary peak finding.
"""
finite(fs, 'sample rate')
if fs <= 0:
raise ValueError('sample rate must be positive')
n = len(values)
if n < 4 or n % 2:
raise ValueError('record must have an even sample count >= 4')
for value in values:
finite(value, 'sample')
if window == 'rect':
weights = [1.0] * n
elif window == 'hann':
weights = [0.5 - 0.5 * math.cos(2 * math.pi * i / n) for i in range(n)]
else:
raise ValueError('window must be rect or hann (periodic Hann)')
weighted = [v * w for v, w in zip(values, weights)]
scale = math.fsum(weights)
result = []
for k in range(n // 2 + 1):
real = math.fsum(v * math.cos(2 * math.pi * k * i / n) for i, v in enumerate(weighted))
imag = math.fsum(-v * math.sin(2 * math.pi * k * i / n) for i, v in enumerate(weighted))
factor = 1 if k in (0, n // 2) else 2
result.append((k * fs / n, factor * abs(complex(real, imag)) / scale))
return result
def write_csv(path, header, rows):
with path.open('w', newline='', encoding='utf-8') as stream:
writer = csv.writer(stream, lineterminator='\n')
writer.writerow(header)
writer.writerows(rows)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--sample-rate', type=float, default=1024.0)
parser.add_argument('--samples', type=int, default=1024)
parser.add_argument('--f1', type=float, default=100.0)
parser.add_argument('--f2', type=float, default=104.0)
parser.add_argument('--amplitude1', type=float, default=1.0)
parser.add_argument('--amplitude2', type=float, default=1.0)
parser.add_argument('--phase2', type=float, default=0.0)
parser.add_argument('--window', choices=['rect', 'hann'], default='rect')
parser.add_argument('--out-dir', type=Path, default=Path('beat-results'))
args = parser.parse_args()
try:
x = make_trace(args.sample_rate, args.samples, args.f1, args.f2, args.amplitude1, args.amplitude2, args.phase2)
spectrum = amplitudes(x, args.sample_rate, args.window)
squared = amplitudes([v * v for v in x], args.sample_rate, args.window)
except ValueError as exc:
parser.error(str(exc))
args.out_dir.mkdir(parents=True, exist_ok=True)
rows = []
for i, value in enumerate(x):
t = i / args.sample_rate
rows.append((t, value, envelope(t, args.f1, args.f2, args.amplitude1, args.amplitude2, args.phase2), value * value))
write_csv(args.out_dir / 'trace.csv', ['time_s', 'raw_signal_au', 'phasor_magnitude_au', 'squared_signal_au2'], rows)
for name, data in [('spectrum.csv', spectrum), ('squared-spectrum.csv', squared)]:
write_csv(args.out_dir / name, ['frequency_hz', 'one_sided_peak_amplitude'], data)
summary = {'constructed_not_measured': True, 'sample_rate_hz': args.sample_rate, 'samples': args.samples,
'record_duration_s': args.samples / args.sample_rate, 'bin_spacing_hz': args.sample_rate / args.samples,
'frequencies_hz': [args.f1, args.f2], 'window': args.window,
'squared_components_within_nyquist': 2 * max(abs(args.f1), abs(args.f2)) < args.sample_rate / 2,
'squared_spectrum_note': 'Squaring can alias above the sampling limit; default100/104Hz fixture stays below it.',
'sample_mean_square': math.fsum(v * v for v in x) / len(x),
'strongest_raw_bins': sorted(spectrum, key=lambda pair: pair[1], reverse=True)[:8],
'target_compiled': False, 'target_executed': False, 'hardware_tested': False}
(args.out_dir / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')
print(json.dumps(summary, indent=2))
return 0
if __name__ == '__main__':
raise SystemExit(main())
Checks that distinguish the explanations
The supplied tests check the sum/product identity at many nonuniform times, the absence of envelope and midpoint bins in the coherent raw signal, the exact new squared components, undoubled zero and Nyquist endpoints, Hann weighting, distant off-bin leakage, unequal amplitudes and phase. A separate energy check compares the record’s mean square with the sum of the squared one-sided line amplitudes, with the appropriate half factor for interior sinusoidal lines. It tests the normalization, the scaling that converts transform magnitudes into amplitudes.
The finite-record result depends on its controls. An apparent small 4 Hz bin in an off-bin or noisy acquisition would require analysis of leakage, offsets, clipping and detector behavior. This experiment isolates exact formulas so those possibilities do not get confused with the basic identity. It does not establish real instrument accuracy or a hardware detection threshold.
Challenge and answer
Challenge: Add equal, zero-phase 200 and 206 Hz cosines. What are the signed multiplier frequency, magnitude-envelope repetition and raw positive-frequency lines? Which low-frequency component appears after squaring? Would a 128-sample record at 1024 samples per second be a convincing way to separate the raw lines?
Answer
The signed multiplier is a 3 Hz cosine around the 203 Hz fast factor. Its magnitude peaks repeat at 6 Hz. The raw positive-frequency lines remain at 200 and 206 Hz. Squaring creates a 6 Hz difference component plus a constant and higher-frequency terms. The short record has 8 Hz bin spacing and insufficient duration to resolve this pair convincingly. Extending the record improves the separation experiment; drawing a slow envelope does not supply a new raw spectral line.
Primary references and further reading
National Institute of Standards and Technology (NIST), Digital Library of Mathematical Functions, equation 4.21.8 supplies the cosine sum identity used here. The numerical examples, controls, figures and tests in this lesson are original calculations from that identity.
NumPy 2.3 official discrete-transform documentation records the forward-transform sign convention and positive/negative-frequency ordering. This program implements a direct transform without importing NumPy. SciPy’s official Hann-window documentation distinguishes symmetric and periodic weighting; the periodic formula used here is stated explicitly in the article and code.
Continue with Tricky Circuit Learn and the separate Circuitpedia. This local article proposes terminology for later coordinated dictionary work; it does not claim a live dictionary change.