TExcelTAD
Home › Fourier Analysis & Signals › Signals with NumPy

Signals with NumPy

On a computer a signal is an array of samples taken at a fixed sampling rate fsf_s (samples per second). The time of sample nn is tn=n/fst_n = n / f_s. This lesson sets up the NumPy habits used in every later lesson: building time axes, generating tones and noise, measuring signals, and printing results readably.

A time axis and a tone

Two ways to build the time axis, and the difference matters:

python · try it yourself
import numpy as np

fs = 8                                     # 8 samples per second (tiny, to print everything)
t1 = np.arange(0, 1, 1 / fs)               # 8 samples, endpoint excluded
t2 = np.linspace(0, 1, fs, endpoint=False) # the same 8 samples
t3 = np.linspace(0, 1, fs)                 # 8 samples INCLUDING t = 1: spacing is 1/7, not 1/8
print(t1.tolist())
print(np.allclose(t1, t2), " spacing of t3:", round(t3[1] - t3[0], 4))

x = np.cos(2 * np.pi * 1 * t1)             # 1 Hz cosine, one full period
print((np.round(x, 3) + 0.0).tolist())
[0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
True  spacing of t3: 0.1429
[1.0, 0.707, 0.0, -0.707, -1.0, -0.707, 0.0, 0.707]

For periodic signals and the FFT you want the endpoint excluded: the sample at t=1t = 1 would repeat the one at t=0t = 0.

Measuring a signal

The quantities used throughout the course:

  • mean (DC component) 1N∑xn\frac{1}{N}\sum x_n,
  • energy ∑xn2\sum x_n^2 and power 1N∑xn2\frac{1}{N}\sum x_n^2,
  • RMS power\sqrt{\text{power}}; a sine of amplitude AA has RMS A/2A/\sqrt{2},
  • SNR in decibels, 10log⁡10(Psignal/Pnoise)10 \log_{10}(P_\text{signal} / P_\text{noise}).
python · try it yourself
import numpy as np

fs = 1000
t = np.arange(0, 1, 1 / fs)
s = 2.0 * np.sin(2 * np.pi * 5 * t)
rng = np.random.default_rng(1)
noise = 0.5 * rng.normal(size=t.size)
x = s + noise

power = lambda v: np.mean(v ** 2)
print(f"mean of s: {abs(np.mean(s)):.4f}   RMS of s: {np.sqrt(power(s)):.4f}  (2/sqrt 2 = {2 / np.sqrt(2):.4f})")
print(f"noise power: {power(noise):.4f}")
print(f"SNR: {10 * np.log10(power(s) / power(noise)):.2f} dB")
mean of s: 0.0000   RMS of s: 1.4142  (2/sqrt 2 = 1.4142)
noise power: 0.2439
SNR: 9.14 dB

The signal power is A2/2=2A^2/2 = 2 and the noise power about 0.52=0.250.5^2 = 0.25, so the SNR is about 10log⁡108≈910 \log_{10} 8 \approx 9 dB.

Printing complex results

Fourier transforms produce complex numbers. Rounding and converting with .tolist() keeps the output short; the + 0.0 turns a negative zero -0.0 into 0.0:

python · try it yourself
import numpy as np

x = np.array([1.0, 2.0, 0.0, -1.0])
X = np.fft.fft(x)
print(np.round(X, 3).tolist())
print("magnitudes:", (np.round(np.abs(X), 3) + 0.0).tolist())
print("phases (rad):", (np.round(np.angle(X), 3) + 0.0).tolist())
[(2+0j), (1-3j), 0j, (1+3j)]
magnitudes: [2.0, 3.162, 0.0, 3.162]
phases (rad): [0.0, -1.249, 0.0, 1.249]

In software

  • Audio files store samples at 44100 or 48000 Hz; scipy.io.wavfile.read returns exactly such arrays. ECG monitors sample around 250-1000 Hz, accelerometers in phones around 100-400 Hz.
  • The SciPy and NumPy FFT modules expect the time axis to be uniformly spaced; irregular samples need resampling or a Lomb-Scargle periodogram.

Exercises

Exercise 1: Number of samples

How many samples does 2.5 seconds of audio at 48 kHz contain, and what is the time between samples?

Answer

120000 samples, about 20.8 microseconds apart.

Solution

N=2.5⋅48000=120000N = 2.5 \cdot 48000 = 120000, and Δt=1/48000≈2.083⋅10−5\Delta t = 1 / 48000 \approx 2.083 \cdot 10^{-5} s.

Exercise 2: RMS of a square wave (code)

A square wave alternates between +1+1 and −1-1. What is its RMS, and how does it compare with a sine of amplitude 1?

Answer

RMS 1.0 versus about 0.7071 for the sine.

Solution
python · try it yourself
import numpy as np
t = np.arange(0, 1, 1 / 1000)
sq = np.sign(np.sin(2 * np.pi * 4 * t + 0.1))
print(round(float(np.sqrt(np.mean(sq ** 2))), 4), round(float(np.sqrt(np.mean(np.sin(2 * np.pi * 4 * t) ** 2))), 4))
1.0 0.7071

Every sample of the square wave has magnitude 1, so its RMS is 1; the sine spends time near 0, so its RMS is only 1/21/\sqrt{2}. (The phase 0.1 avoids samples exactly at the zero crossings, where np.sign would return 0.)

Exercise 3: Decibels

If the noise power doubles, how many decibels does the SNR drop?

Answer

About 3 dB.

Solution

10log⁡102≈3.0110 \log_{10} 2 \approx 3.01, so doubling the noise power lowers the SNR by about 3 dB; a factor of 10 in power is 10 dB.

Test yourself

Why use np.arange(0, 1, 1/fs) instead of np.linspace(0, 1, fs) for one period?

  1. it is faster
  2. it excludes the endpoint, so the period is not repeated and the spacing is exactly 1/fs1/f_s
  3. it gives more samples
  4. linspace cannot make floats

A sine wave of amplitude AA has RMS…

  1. AA
  2. A/2A/2
  3. A/2A/\sqrt{2}
  4. 2A\sqrt{2}A

An SNR of 20 dB means the signal power is…

  1. 20 times the noise power
  2. 100 times the noise power
  3. 2 times
  4. equal