s LearnSqueak.com

SMALLTALK LAB

Discrete Fourier transform: find frequencies in a sample array

Build a direct DFT from cosine and sine projections in native Squeak. Keep real and imaginary coefficients as pairs, reconstruct the samples, and distinguish frequency bins from amplitude, aliasing and leakage.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use a native Squeak 6.1 Workspace and Print it on each complete checkpoint. All eight run independently without external packages. Inputs are finite real-valued samples with equal spacing. Float results are checked with tolerances, so expected results remain reproducible booleans. Use Do it for the separate Morphic board, choosing stage 0 through 4.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.

01 - Index time samples from zero, arrays from one

A DFT describes N equally spaced samples as N frequency bins. Mathematical sample j and bin k run from 0 through N-1, while their Squeak array positions are j+1 and k+1. At sampling rate fs, bin k has frequency k*fs/N Hz, interpreted modulo fs. Here N=8 and fs=800 Hz, so adjacent bins are 100 Hz apart.

Independent Workspace expression - select all, then Print it
| count sampleRate signal |
count := 8. sampleRate := 800.
signal := (0 to: count - 1) collect: [:j |
 (2.0 * Float pi * j / count) cos].
{sampleRate / count.
 (signal first - 1.0) abs < 1.0e-10.
 (signal at: 3) abs < 1.0e-10.
 ((signal at: 5) + 1.0) abs < 1.0e-10}

Expected: #(100 true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Index time samples from zero, arrays from one
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try a two-cycle cosine by multiplying the angle by 2. Its quarter-record sample is -1, not zero. The record duration is N/fs, although its last sample time is (N-1)/fs.

Download this checkpoint

02 - Project onto cosine and negative sine

For each bin, sum x[j]*cos(2*pi*k*j/N) for the real part and -x[j]*sin(2*pi*k*j/N) for the imaginary part. The minus sign fixes our forward-transform convention. A positive sine at bin 1 therefore has a negative imaginary coefficient. Orthogonality makes other integer-frequency projections cancel, up to rounding.

Independent Workspace expression - select all, then Print it
| count real imaginary angle sample |
count := 8. real := 0.0. imaginary := 0.0.
0 to: count - 1 do: [:j |
 angle := 2.0 * Float pi * j / count.
 sample := angle sin.
 real := real + (sample * angle cos).
 imaginary := imaginary - (sample * angle sin)].
{real abs < 1.0e-10. (imaginary + 4.0) abs < 1.0e-10}

Expected: #(true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Project onto cosine and negative sine
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try cosine instead of sine: real becomes 4 and imaginary becomes approximately zero. These raw coefficients are not yet sinusoid amplitudes.

Download this checkpoint

03 - Store the full transform as real/imaginary pairs

No complex-number package is needed: bin k is a two-element array at position k+1. This forward transform has no normalization. A constant 2 produces DC coefficient 16 for eight samples; a unit cosine adds real coefficients 4 at bins 1 and 7. Those two bins jointly describe one real cosine.

Independent Workspace expression - select all, then Print it
| dft samples bins |
dft := [:dftSamples |
 | dftCount |
 dftCount := dftSamples size.
 dftCount = 0 ifTrue: [Error signal: 'Need at least one sample'].
 (0 to: dftCount - 1) collect: [:dftK |
  | dftReal dftImaginary dftAngle |
  dftReal := 0.0. dftImaginary := 0.0.
  0 to: dftCount - 1 do: [:dftJ |
   dftAngle := 2.0 * Float pi * dftK * dftJ / dftCount.
   dftReal := dftReal + ((dftSamples at: dftJ + 1) * dftAngle cos).
   dftImaginary := dftImaginary - ((dftSamples at: dftJ + 1) * dftAngle sin)].
  {dftReal. dftImaginary}]].
samples := (0 to: 7) collect: [:j |
 2.0 + (2.0 * Float pi * j / 8) cos].
bins := dft value: samples.
{((bins first first) - 16.0) abs < 1.0e-10.
 ((bins at: 2) first - 4.0) abs < 1.0e-10.
 ((bins at: 8) first - 4.0) abs < 1.0e-10.
 bins allSatisfy: [:pair | pair second abs < 1.0e-10]}

Expected: #(true true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Store the full transform as real/imaginary pairs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try changing the offset from 2 to 3. Only DC should change. The block rejects empty input; provide finite real numbers, not NaN or infinity.

Download this checkpoint

04 - Read magnitude without losing the mirror bin

Magnitude is sqrt(real squared + imaginary squared). For real input, bin N-k is the complex conjugate of bin k: equal real part and opposite imaginary part. At a non-DC, non-Nyquist bin, an isolated bin-centered sinusoid of amplitude A gives magnitude N*A/2 in each member of the pair. DC and, for even N, Nyquist are unpaired and must not be doubled.

Independent Workspace expression - select all, then Print it
| dft bins pair mirror magnitude |
dft := [:dftSamples |
 | dftCount |
 dftCount := dftSamples size.
 dftCount = 0 ifTrue: [Error signal: 'Need at least one sample'].
 (0 to: dftCount - 1) collect: [:dftK |
  | dftReal dftImaginary dftAngle |
  dftReal := 0.0. dftImaginary := 0.0.
  0 to: dftCount - 1 do: [:dftJ |
   dftAngle := 2.0 * Float pi * dftK * dftJ / dftCount.
   dftReal := dftReal + ((dftSamples at: dftJ + 1) * dftAngle cos).
   dftImaginary := dftImaginary - ((dftSamples at: dftJ + 1) * dftAngle sin)].
  {dftReal. dftImaginary}]].
bins := dft value: ((0 to: 7) collect: [:j |
 3.0 * (2.0 * Float pi * j / 8) sin]).
pair := bins at: 2. mirror := bins at: 8.
magnitude := (pair first squared + pair second squared) sqrt.
{(pair first - mirror first) abs < 1.0e-10.
 (pair second + mirror second) abs < 1.0e-10.
 (pair second + 12.0) abs < 1.0e-10.
 (2.0 * magnitude / 8 - 3.0) abs < 1.0e-10}

Expected: #(true true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Read magnitude without losing the mirror bin
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try amplitude 0.5. Magnitude alone discards phase: a sine and cosine of the same amplitude have the same magnitude spectrum, but different pairs.

Download this checkpoint

05 - Reconstruct every sample with the inverse sign

The inverse uses the positive exponential and divides by N exactly once. Its real contribution from a pair (a,b) is a*cos(angle) - b*sin(angle). Summing all bins reconstructs real samples. The inverse block returns only the real component; it assumes a conjugate-symmetric spectrum, as produced by our DFT of real input.

Independent Workspace expression - select all, then Print it
| dft inverse samples bins rebuilt |
dft := [:dftSamples |
 | dftCount |
 dftCount := dftSamples size.
 dftCount = 0 ifTrue: [Error signal: 'Need at least one sample'].
 (0 to: dftCount - 1) collect: [:dftK |
  | dftReal dftImaginary dftAngle |
  dftReal := 0.0. dftImaginary := 0.0.
  0 to: dftCount - 1 do: [:dftJ |
   dftAngle := 2.0 * Float pi * dftK * dftJ / dftCount.
   dftReal := dftReal + ((dftSamples at: dftJ + 1) * dftAngle cos).
   dftImaginary := dftImaginary - ((dftSamples at: dftJ + 1) * dftAngle sin)].
  {dftReal. dftImaginary}]].
inverse := [:invBins |
 | invCount |
 invCount := invBins size.
 (0 to: invCount - 1) collect: [:invJ |
  | invSum invAngle invPair |
  invSum := 0.0.
  0 to: invCount - 1 do: [:invK |
   invAngle := 2.0 * Float pi * invK * invJ / invCount.
   invPair := invBins at: invK + 1.
   invSum := invSum + (invPair first * invAngle cos)
    - (invPair second * invAngle sin)].
  invSum / invCount]].
samples := #(2 -1 4 0 3 -2 1 5).
bins := dft value: samples.
rebuilt := inverse value: bins.
(1 to: samples size) allSatisfy: [:index |
 ((rebuilt at: index) - (samples at: index)) abs < 1.0e-9]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Reconstruct every sample with the inverse sign
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try a one-element signal or an odd-length array. The round trip still works. Dropping the division by N multiplies the reconstructed signal by N.

Download this checkpoint

06 - Demonstrate aliasing before interpreting frequencies

Sampling cannot uniquely recover arbitrary continuous signals. At fs=800 Hz, a 700 Hz cosine and a 100 Hz cosine produce the same samples: 700 is congruent to -100 modulo 800, and cosine is even. For even N, bin N/2 is Nyquist at fs/2. Bins above it represent negative frequencies; they are not independent higher-frequency evidence.

Independent Workspace expression - select all, then Print it
| sampleRate low high |
sampleRate := 800. low := 100. high := 700.
(0 to: 15) allSatisfy: [:j |
 ((2.0 * Float pi * low * j / sampleRate) cos
  - (2.0 * Float pi * high * j / sampleRate) cos)
   abs < 1.0e-10]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Demonstrate aliasing before interpreting frequencies
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try 900 Hz in place of 700 Hz: it also aliases to 100 Hz. To avoid aliasing before sampling, band-limit below fs/2; analyzing more bins afterward cannot undo it. A sine exactly at Nyquist can even sample to all zeros.

Download this checkpoint

07 - See leakage from a non-integer number of cycles

A DFT treats the finite record as one period of a repeating sequence. A sinusoid with an integer number of cycles fits that period and occupies its matching bins. A 1.5-cycle sine does not fit: its energy spreads across bins. This is spectral leakage, not evidence of many physical oscillators. The finite rectangular observation window causes it, often accompanied by a boundary mismatch.

Independent Workspace expression - select all, then Print it
| dft centered offGrid energyOutside |
dft := [:dftSamples |
 | dftCount |
 dftCount := dftSamples size.
 dftCount = 0 ifTrue: [Error signal: 'Need at least one sample'].
 (0 to: dftCount - 1) collect: [:dftK |
  | dftReal dftImaginary dftAngle |
  dftReal := 0.0. dftImaginary := 0.0.
  0 to: dftCount - 1 do: [:dftJ |
   dftAngle := 2.0 * Float pi * dftK * dftJ / dftCount.
   dftReal := dftReal + ((dftSamples at: dftJ + 1) * dftAngle cos).
   dftImaginary := dftImaginary - ((dftSamples at: dftJ + 1) * dftAngle sin)].
  {dftReal. dftImaginary}]].
centered := dft value: ((0 to: 15) collect: [:j |
 (2.0 * Float pi * j / 16) sin]).
offGrid := dft value: ((0 to: 15) collect: [:j |
 (2.0 * Float pi * 1.5 * j / 16) sin]).
energyOutside := [:bins |
 | sum |
 sum := 0.0.
 0 to: 15 do: [:k |
  (k = 1 or: [k = 15]) ifFalse: [
   sum := sum + (bins at: k + 1) first squared
    + (bins at: k + 1) second squared]].
 sum].
{(energyOutside value: centered) < 1.0e-15.
 (energyOutside value: offGrid) > 1.0}

Expected: #(true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: See leakage from a non-integer number of cycles
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try 2 cycles and change the excluded bins to 2 and 14. Windowing can reduce distant sidelobes but broadens peaks and changes amplitude scaling. Zero-padding gives denser frequency samples, not more information or better true resolution.

Download this checkpoint

08 - Verify energy and count the actual work

Parseval provides a second numerical check: sum of sample squares equals sum of squared bin magnitudes divided by N for this normalization. The direct DFT visits every (k,j) pair, exactly N squared times. The inverse does the same. This is an educational O(N squared) algorithm with O(N) output storage, not an FFT. FFT algorithms compute the same transform faster, commonly O(N log N).

Independent Workspace expression - select all, then Print it
| dft samples bins timeEnergy binEnergy visits |
dft := [:dftSamples |
 | dftCount |
 dftCount := dftSamples size.
 dftCount = 0 ifTrue: [Error signal: 'Need at least one sample'].
 (0 to: dftCount - 1) collect: [:dftK |
  | dftReal dftImaginary dftAngle |
  dftReal := 0.0. dftImaginary := 0.0.
  0 to: dftCount - 1 do: [:dftJ |
   dftAngle := 2.0 * Float pi * dftK * dftJ / dftCount.
   dftReal := dftReal + ((dftSamples at: dftJ + 1) * dftAngle cos).
   dftImaginary := dftImaginary - ((dftSamples at: dftJ + 1) * dftAngle sin)].
  {dftReal. dftImaginary}]].
samples := #(2 -1 4 0 3 -2 1 5).
bins := dft value: samples.
timeEnergy := samples inject: 0.0 into: [:sum :x | sum + x squared].
binEnergy := bins inject: 0.0 into: [:sum :pair |
 sum + pair first squared + pair second squared].
visits := 0.
0 to: samples size - 1 do: [:k |
 0 to: samples size - 1 do: [:j | visits := visits + 1]].
{(timeEnergy - (binEnergy / samples size)) abs < 1.0e-9.
 visits. (samples size * 2) squared}

Expected: #(true 64 256)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Verify energy and count the actual work
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try doubling N: pair visits quadruple. The count excludes test code and signal construction. Tolerances here suit small bounded inputs; for larger magnitudes and sizes use scale-aware error bounds.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Discrete Fourier transform: find frequencies in a sample array native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

Array positions are one-based; DFT indices are zero-based. The coefficient for k lives at k+1. Evaluate trigonometric arguments in radians, not degrees.

Our forward imaginary sum has a minus sign. The inverse divides by N and uses a*cos - b*sin for its real part. Mixing conventions or normalizing both transforms breaks reconstruction.

A raw coefficient magnitude is not automatically an amplitude. Doubling magnitude/N is correct for an isolated real bin-centered sinusoid away from DC and Nyquist. It is not a general amplitude estimator for leaking or overlapping peaks.

The inverse shown extracts the real part. Arbitrarily editing bins can destroy conjugate symmetry and create a nonzero imaginary inverse component that this code does not report. Preserve conjugate pairs for real-signal filtering.

Bin spacing fs/N and Nyquist fs/2 are different limits. Longer records can improve frequency discrimination; a higher sampling rate can raise the non-aliased range when paired with appropriate analog filtering.

Leakage is caused by finite observation. Windowing trades narrower peaks for lower distant sidelobes and needs amplitude corrections. Zero-padding does not replace a longer observation.

The direct transform performs N squared sample-bin accumulations and stores N pairs. It is not suitable for large real-time audio blocks compared with an FFT. Tiny residual coefficients are floating-point roundoff, not exact zeros.

Three practice challenges

Decode a mixed signal

For N=16 samples of 2 + 3*cos(2*pi*j/16) + 4*sin(2*pi*3*j/16), predict every nonzero pair before running the DFT. Then check your prediction within a tolerance.

Show solution

DC (k=0) is (32,0). Bins 1 and 15 are (24,0). Bin 3 is (0,-32) and bin 13 is (0,32). All other pairs are approximately (0,0). The mean is 32/16=2; doubling the magnitudes of the positive-frequency pairs and dividing by 16 recovers amplitudes 3 and 4. Use array positions 1, 2, 16, 4 and 14 respectively.

Filter without losing the mirror

Transform the mixed signal from the previous exercise. Remove its three-cycle sine while preserving the mean and one-cycle cosine. Which pairs must you change, and how should you test the result?

Show solution

Replace both bin 3 and bin 13, at array positions 4 and 14, with #(0.0 0.0). Run the inverse and compare each sample with 2 + 3*cos(2*pi*j/16) using absolute error below 1.0e-9. Removing only bin 3 breaks conjugate symmetry and leaves half the real sine contribution plus an imaginary inverse component that our real-only inverse omits. This ideal bin removal is valid for the bin-centered fixture, not a universal noise-removal technique.

Separate resolution from sampling rate

At fs=800 Hz compare N=16 and N=80. What are the record duration, bin spacing and Nyquist limit? Would padding the 16 samples with zeros to length 80 give the same information as acquiring 80 samples?

Show solution

N=16 gives duration 0.02 s and 50 Hz spacing. N=80 gives duration 0.1 s and 10 Hz spacing. Nyquist remains 400 Hz in both cases. Zero-padding the short record makes a denser grid of its existing finite-record spectrum but does not create the missing 0.08 s of measurements or the resolving ability of the longer observation. Both records still require anti-alias filtering before sampling.

Continue learning

Sound Sequencer | Discrete Convolution | Online Variance

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.