The last figure of E1 was the spectrum of a sawtooth wave: frequency along the x axis, and wherever there is a peak the sound contains that frequency. That figure was computed with the DFT. In this exercise we write the DFT ourselves. It has five parts: generate a real sinusoid, generate a complex sinusoid, write the DFT, write the inverse DFT, and compute the magnitude spectrum.
Sinusoids
E1 explained that a sound in the computer is a string of numbers sampled at a sampling rate fs. The simplest sound is a sinusoid, and gen_sine, the function of part 1, generates one: given amplitude A, frequency f, phase φ, sampling rate fs and duration t, it returns that string of numbers.
A cosine can be seen as a point going round a circle at a steady speed, and we only look at its horizontal position. f is how many turns per second, fs is how many samples per second, so with every sample the point turns 360° × f ÷ fs. A is the radius of the circle, and decides how loud the sound is. φ is the starting position: the point begins at angle φ.
On the left is the turning point: the blue dot is where it is now, the orange dot is its horizontal position. On the right, grey is the continuous cosine, the blue stems are the fs × t = 10 sampled numbers, and the orange one is the current sample. The exercise’s example is A = 1, f = 10, φ = 1, fs = 50: each step turns 72°, and the first 5 values are 0.540, −0.633, −0.932, 0.057, 0.967, the same as the exercise gives. The first value is cos(1), because at n = 0 the angle is just φ.
As a formula:
$$ x[n] = A\cos(2\pi f n / fs + \varphi) $$n is the sample index, 0, 1, 2 and so on; n / fs is the time of sample n; 2π f n / fs is the angle turned up to that moment, in radians, where one turn is 2π. The number of samples is fs per second times the duration t.
Phase
Drag φ from 0 to π/2: the starting position on the circle moves from the far right to the top, and the whole wave on the right shifts to the left, with no change in height or speed. With φ = 0 the first value is cos 0 = 1 and the wave starts at its peak; with φ = π/2 the first value is 0. One turn of a 10 Hz wave takes 0.1 s, a quarter turn is 0.025 s, so the wave shifted by 0.025 s.
Listening to one tone on its own, phase cannot be heard. It only matters when tones are added together: two identical waves half a turn apart go up and down in opposition and cancel when added, which is what noise-cancelling headphones use.
Implementation
def gen_sine(A, f, phi, fs, t):
N = int(fs * t)
n = np.arange(N)
return A * np.cos(2 * np.pi * f * n / fs + phi)
np.cos works on the whole array at once, element by element, so no loop is needed.
Aliasing again
E1 explained that the sampling rate must be more than twice the signal frequency, or aliasing occurs. With fs = 50 the highest representable frequency is 25 Hz, and the exercise asks which of 20 Hz and 30 Hz is a problem.
Drag f to 30 and a dashed green line appears on the right: the 20 Hz wave, with every orange sample landing on it. The computer only stores those samples, so it cannot tell whether the original was 30 Hz or 20 Hz; after sampling, 30 Hz has become 50 − 30 = 20 Hz.
The left side shows why. 30 Hz turns 216° per sample and 20 Hz turns 144°; 216° anticlockwise and 144° clockwise end at the same place, so the two points turn equally fast in opposite directions. A cosine only records the horizontal position, two points turning in opposite directions have the same horizontal position, and so they cannot be told apart.
Complex sinusoids
The point above keeps turning, but the cosine only recorded its horizontal position and lost the vertical one. Recording the vertical position too gives a complex sinusoid, which part 2 generates.
Complex numbers
A complex number a + bj is a point in the plane: a is the real part, the left-right position; b is the imaginary part, the up-down position; j is a marker saying that this number belongs to the up-down direction. 0.8 + 0.6j is the point reached from the origin by going 0.8 to the right and 0.6 up. In Python, j is written 1j.
The point on the circle at angle θ has horizontal position cos θ and vertical position sin θ, so as a complex number it is cos θ + j sin θ. This point has a shorthand, \(e^{j\theta}\):
$$ e^{j\theta} = \cos\theta + j\sin\theta $$This is Euler’s formula. Wherever \(e^{j\theta}\) appears below, read it as the point on the circle at angle θ. In Python it is np.exp(1j * theta): np.exp(1j * 0) is 1, the far right; np.exp(1j * np.pi / 2) is j, the top; np.exp(1j * np.pi) is −1, the far left.
Generating a complex sinusoid
The complex sinusoid the exercise wants has only two parameters: N is the number of points, and k is how many turns those N points make in all. One turn is 2π, k turns is 2πk, spread over N steps, so each step turns 2πk / N. The angle of point n is 2πkn / N:
$$ \bar{x}[n] = e^{j2\pi kn/N}, \quad n = 0, \dots, N-1 $$On the left are the N points on the circle, the current one in orange, with a dashed arc showing the angle it turns to reach the next point. On the right the horizontal and vertical positions of each point are drawn separately: the horizontal positions joined up are a cos, the vertical ones a sin. With k = 1 and N = 5 each step turns 72°, which is 2π/5 = 1.257 rad, the phase increment between consecutive samples that the exercise asks for.
Drag k to 4. The 5 points sit in the same 5 places, in reverse order. 288° anticlockwise and 72° clockwise end at the same place, so k = 4 turns as fast as k = 1 in the opposite direction, and can be seen as k = −1. On the right the cos row is unchanged and the sin row is flipped upside down. Two complex numbers with the same real part and opposite imaginary parts are called conjugates. This is the same thing as 30 Hz turning into 20 Hz above, with 5 − 4 = 1 matching 50 − 30 = 20; the difference is that here the vertical position was not lost, the direction of turning is still there, and k = 1 and k = 4 can be told apart.
Implementation
def gen_complex_sine(k, N):
n = np.arange(N)
return np.exp(1j * 2 * np.pi * k * n / N)
The only difference from gen_sine is that np.cos became np.exp(1j * ...): the former takes only the horizontal position, the latter the whole point. The amplitude is fixed at 1 and the starting position at 0.
The DFT
What the DFT does
Use gen_sine to make three notes, do at 262 Hz, mi at 330 Hz and sol at 392 Hz, with amplitudes 1, 0.6 and 0.4, and add them into a chord.
The upper figure is the sum, which is the sound actually recorded, and from this line alone you cannot tell how many notes are in it. The lower figure is its magnitude spectrum, with peaks only at 262, 330 and 392; the 262 peak is the highest and the 392 one the lowest, matching the three amplitudes. The buttons remove a note, and its peak disappears.
What the DFT does is find how much of each frequency a sound contains, like tasting a mixed juice and saying how many parts apple, orange and grape are in it. Most of the rest of this course is built on spectra.
The DFT as scoring
To find out whether a sound contains 262 Hz, generate a 262 Hz cosine yourself, multiply it with the sound point by point, and add up all the products to get a score. A high score means the frequency is there; a score of 0 means it is not. This wave of known frequency, made only for comparison, is called the reference wave below.
In the top row, blue is the signal and dashed orange is the reference wave, both 32 points long. The middle row is the point-by-point products, green positive and orange negative. The bottom row adds the products up from left to right, and the number at the right end is the score. The figure on the right comes in the next section.
When the frequencies match, the reference goes up when the signal goes up, positive times positive is positive; it goes down when the signal goes down, negative times negative is still positive. The whole middle row is green, the sum climbs all the way, and ends at 16, exactly half the number of points.
Press “Different frequency” to change the reference to k = 5. The two waves are sometimes in step and sometimes opposed, the middle row has green and orange in exactly equal amounts, and the sum is 0.
Press “Same frequency, signal is a sin”. The signal and the reference have the same frequency, but their starting positions are a quarter turn apart, the products are again half positive and half negative, and the score is 0. Using only a cos reference misses this case, so every frequency is scored twice, once with a cos reference and once with a sin reference. Click “sin reference” and this case gets full marks.
Scoring every frequency from k = 0 to N − 1 twice this way is the DFT. Every bar in the chord figure was computed like this.
Two scores in one complex number
The figure on the right puts the two scores together: the x coordinate is the cos score and the y coordinate is minus the sin score, and that point is X[k]. A point’s position can be given as 3 m east and 4 m north, or as 5 m to the north-east; the former is real and imaginary part, the latter magnitude and angle, and they describe the same point.
- The magnitude |X[k]| is the distance from the origin, the two scores combined, and says how strong the frequency k component is;
- the angle says whether the score came mainly from the cos reference or the sin reference, which is where this component starts, that is, its phase.
Drag the signal’s phase φ: the point goes round the origin and its distance from the origin stays the same. Whether the signal is a cos or a sin, the strength is the same and only the starting position differs by a quarter turn, so the angle of X[k] differs by 90°.
As a formula:
$$ X[k] = \sum_{n=0}^{N-1} x[n]\,e^{-j2\pi kn/N}, \quad k = 0, \dots, N-1 $$\(e^{-j2\pi kn/N}\) is the point turning the other way, which by Euler’s formula equals cos(2πkn/N) − j sin(2πkn/N). Multiply it in and add up: the real part is the cos score and the imaginary part is minus the sin score, the same as the point in the figure.
By hand
The exercise uses x = [1, 2, 3, 4], N = 4.
For k = 0 the reference turns 0° per step, the cos reference is all 1 and the sin reference all 0, so X[0] is the sum of the four numbers, 10.
For k = 1 the reference makes 1 turn in 4 points, 90° per step:
| n | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| x[n] | 1 | 2 | 3 | 4 |
| cos reference | 1 | 0 | −1 | 0 |
| sin reference | 0 | 1 | 0 | −1 |
cos score = 1×1 + 2×0 + 3×(−1) + 4×0 = −2
sin score = 1×0 + 2×1 + 3×0 + 4×(−1) = −2
X[1] = −2 − j × (−2) = −2 + 2j
k = 2 and k = 3 go the same way, and the result is [10, −2+2j, −2, −2−2j]. For k = 2 the cos reference is [1, −1, 1, −1] and the sin reference is all 0.
Implementation
Scoring once for every k, written directly as code:
def dft(x):
N = len(x)
n = np.arange(N)
X = []
for k in range(N):
ref = np.exp(-1j * 2 * np.pi * k * n / N)
X.append(np.sum(x * ref))
return np.array(X)
| Formula | Code |
|---|---|
| for every k | for k in range(N) |
| \(e^{-j2\pi kn/N}\) | np.exp(-1j * 2 * np.pi * k * n / N) |
| \(x[n]\,\cdot\) | x * ref |
| \(\sum\) | np.sum(...) |
np.fft.fft is NumPy’s own DFT; the result is the same, only much faster. Comparing on [1, 2, 3, 4], the largest difference is about 2e−15. A computer keeps only about 16 significant digits of a decimal number, the later digits of π or cos(1) are dropped, and every operation brings in a little error; 0.1 + 0.2 giving 0.30000000000000004 in Python has the same cause. Numbers around 1e−15 can be treated as 0.
What X[0] is
Each of the N numbers the DFT outputs is called a bin: N boxes, one frequency per box. The exercise asks which bin is the DC component.
DC stands for direct current, whose voltage does not swing up and down. The part of a signal that does not swing and stays constant is its DC component. A signal can be split into a fixed height plus a part rising and falling around it, like waves around sea level. [1, 2, 3, 4] splits into [2.5, 2.5, 2.5, 2.5] plus [−1.5, −0.5, 0.5, 1.5], and the sea level is the average, 2.5.
The bin measuring this is k = 0. In the scoring animation drag the reference k to 0: the reference is a horizontal line of all 1s, with no swing at all. Scoring with it just adds all the numbers; the rising and falling part has positives and negatives that add to 0, and only the sea level remains, X[0] = 4 × 2.5 = 10. So X[0] is the sum of all samples, and divided by N it is the average.
The inverse DFT
Rebuilding the signal from the recipe
The DFT breaks a signal into a recipe, where each X[k] says how large the frequency k component is and where it starts. The inverse DFT (IDFT) goes the other way: build the wave of every frequency according to the recipe, add them all together, and the signal is back.
The recipe is the X = [10, −2+2j, −2, −2−2j] computed by hand above. k = 0 builds a horizontal line at height 10 ÷ 4 = 2.5, the sea level. k = 1 and k = 3 are a pair, one turning forwards and one backwards, their vertical positions cancel, and together they make one real wave, [−1, −1, 1, 1]. k = 2 alternates up and down, [−0.5, 0.5, −0.5, 0.5]. The bottom row is the three parts added up, with grey rings for the original signal. Drag n: at n = 0, 2.5 − 1 − 0.5 = 1, and over the four positions the result is exactly [1, 2, 3, 4].
Press X = [1, 1, 1, 1]. This recipe has one part of each of the four frequencies, all the same size and the same starting position. At n = 0 every wave is at its start, every start is at the top, and four quarters add up to 1. At the other positions the four waves turn at different speeds and point in different directions, positive and negative, and cancel exactly to 0, so the result is [1, 0, 0, 0], which is what the exercise asks about.
Implementation
$$ x[n] = \frac{1}{N}\sum_{k=0}^{N-1} X[k]\,e^{j2\pi kn/N}, \quad n = 0, \dots, N-1 $$Three things differ from the DFT:
| DFT | IDFT | |
|---|---|---|
| Sign of the exponent | negative, turning backwards, for scoring | positive, turning forwards, for building waves |
| Factor in front | none | 1/N |
| What the loop runs over | one score per k | one value per n |
def idft(X):
N = len(X)
k = np.arange(N)
x = []
for n in range(N):
wave = np.exp(1j * 2 * np.pi * k * n / N)
x.append(np.sum(X * wave) / N)
return np.array(x)
Why divide by N
For the k = 0 horizontal line, X[0] is 10 but the height built is 2.5. The DFT adds N products together when scoring, so the result is N times too large, and X[0] = N × average is one example; dividing by N when rebuilding restores the original size. This 1/N can go in the DFT, in the IDFT, or as \(1/\sqrt{N}\) on each side, as long as one round trip divides by N in total. This course and NumPy put it in the IDFT.
Round-trip error
DFT then IDFT, idft(dft(x)), should in theory give exactly x. Computed on [1, 2, 3, 4] it gives 1.0000000000000002, 2, 2.9999999999999996, 4, a largest difference of 6e−16, floating-point error again, so the signal can be considered fully restored.
Each number in the result also carries a tiny imaginary part, such as −5.55e−16j, while the original signal is real. In the animation k = 1 and k = 3 are a pair whose imaginary parts, one positive and one negative, cancel when added. The spectrum of a real signal always comes in such pairs, X[N−k] and X[k] are conjugates of each other, and this is called conjugate symmetry. So in theory all imaginary parts cancel to 0, and floating-point error leaves them cancelling slightly short, with a residue around 1e−16. Such a residue can be removed with np.real(), provided the original signal really is real and the remaining imaginary parts really are around 1e−15. When the spectrum is not conjugate symmetric it must not be removed: in idft([1, 2, 3, 4]), X[1] = 2 and X[3] = 4 are not conjugates, the imaginary parts of the result are ±0.5, and that is real information.
The magnitude spectrum
Keeping only the magnitude
Often we only care which frequencies a sound contains and how strong each is, not where they start. Keeping only the magnitude of X[k] and dropping the angle gives the magnitude spectrum. np.abs computes each complex number’s distance from the origin:
def gen_mag_spec(x):
return np.abs(dft(x))
The magnitude spectrum of [1, 2, 3, 4] is [10, 2.83, 2, 2.83]. X[1] = −2 + 2j is 2 to the left and 2 up, and its distance from the origin is \(\sqrt{2^2 + 2^2} \approx 2.83\). The lower half of the chord figure is a magnitude spectrum.
How many Hz is bin k
In the chord example N and fs are both 8000, so k happens to equal the frequency. In general they are not equal. The N bins share the frequency range from 0 to fs equally, each bin is fs / N wide, and the frequency of bin k is:
$$ f = k \cdot \frac{fs}{N} $$The exercise’s signal is a 200 Hz cosine with fs = 1000 and N = 512, so each bin is 1000 / 512 ≈ 1.95 Hz wide.
The upper figure is the whole magnitude spectrum, 512 bins; the lower one zooms in around the highest peak. The highest peak is at k = 102, which converts to 102 × 1000 / 512 ≈ 199.22 Hz, close to 200 Hz but not equal, for the reason given in the last section.
Why there are two peaks
The other peak is at k = 410, and 512 − 102 is exactly 410. Just as k = N − 1 amounts to k = −1, k = 410 amounts to k = −102, turning the other way, which can be called a negative frequency.
One cosine gives two peaks because a real cosine is itself made of two points turning in opposite directions:
$$ \cos\theta = \frac{e^{j\theta} + e^{-j\theta}}{2} $$One goes anticlockwise and one clockwise, they are mirror images top to bottom at every moment, the vertical positions cancel, and only the horizontal position is left, which is the cosine. The DFT finds the two points separately, one at 102 and one at 410. So the magnitude spectrum of a real signal is always symmetric, the second half mirroring the first, and when looking for the peak np.argmax(mX[:N // 2]) searches only the first half.
Halve the amplitude, the spectrum halves
Press A = 0.5. The peaks are still at 102 and 410, and their height goes from 193.9 to 96.95, exactly half. Not only the peak: every point of the magnitude spectrum halves. It is like diluting a glass of juice with the same amount of water: the ingredients are unchanged, there is just half as much of each. In scoring terms, every signal value is multiplied by 0.5, so every product is, and so is the score. This property is called linearity.
A frequency between two bins
The reference wave of every bin makes a whole number of turns in N points: k = 102 makes exactly 102 turns and k = 103 exactly 103, and there is no reference making 102.4 turns. The 200 Hz signal makes 200 × 512 / 1000 = 102.4 turns in 512 points, between 102 and 103.
Press 199.22 Hz. The signal makes exactly 102 turns, coincides with the k = 102 reference from start to end, gets full marks of 256, and every other bin is 0. Full marks are 256 because with amplitude 1 and 512 points the total score would be 512, but a real cosine has two mirrored peaks that take half each, A × N / 2 = 256.
Press 200 Hz again. The signal makes 0.4 turns more than the reference: they line up at the start, drift apart a little with every turn, and by the end are almost half a turn apart, like two people running side by side with one slightly faster, shoulder to shoulder at first and further apart the longer they run. k = 102 lines up with the signal only part of the time, misses full marks, and gets only 194. k = 103 is also close to 102.4 and gets 129. Further bins such as 101, 104 and 105 also get some, less the further away they are. Energy that should sit in one bin spreads into many neighbouring bins, and this is called spectral leakage.
The mismatch between 199.22 Hz and 200 Hz above has the same cause. Bins can only sit at multiples of 1.95 Hz, 200 Hz is not one of them, and it can only be represented by the nearest bin, number 102.
Summary
- A cosine is the horizontal position of a point going round a circle, turning 360° × f ÷ fs per sample, with φ the starting position;
- a complex number is a point in the plane, \(e^{j\theta}\) is the point on the circle at angle θ, a complex sinusoid is a string of turning points making k turns in N points, and k = N − 1 is one turn the other way;
- the DFT is scoring: multiply the signal point by point with the cos and sin reference waves of each frequency and add up, a high score when the frequencies match and cancellation to 0 when they do not;
- |X[k]| is the strength of frequency k, its angle is the phase, and X[0] is N times the average;
- the inverse DFT adds the wave of each frequency back according to the recipe and finally divides by N;
- bin k corresponds to k · fs / N Hz, the magnitude spectrum of a real signal is symmetric, and a frequency between two bins leaks into the neighbouring bins.
Exercise source: E2-Sinusoids-and-DFT.ipynb