Stooges4
Stooges4

Reputation: 103

How to Use Numpy.FFT on A Pulsed Signal

I am just starting to learn numpy.fft, so apologies in advance. I have an array consisting of 1000 elements of 1s and 0s, representing 1000ms of pulsed input consisting of trues and falses. I wanted to perform rfft on this array. For a simple example, I created this array that has a 1 on every 3rd element and 0 otherwise:

freq = 3
for j in range(0, 1000):
    if freq != 0 and (((j + 1) % freq) == 0):
        arr3hz.append(1)
    else:
        arr3hz.append(0)

I was expecting rfft to give me 3Hz somehow, I used this code:

n = len(arr3hz)
d = 1 / 1000
hs = np.fft.rfft(arr3hz)
fs = np.fft.rfftfreq(n, d)
amps = np.absolute(hs)

for j in range(0, len(fs)):
    fw.write("Freq: %d Amp: %f\n" % (fs[j], amps[j]))

On my written file, I am just seeing random frequency elements with random amplitudes, which I was not able to make sense of. What is wrong with my use of numpy.rfft? I was also not sure of what to use for n and d as well for an array like this.

Upvotes: 3

Views: 286

Answers (1)

Subhaneil Lahiri
Subhaneil Lahiri

Reputation: 458

There are a few things going on here.

  1. The first block gives a period of 3 ms, i.e. a frequency of 333.33 Hz
  2. The mean is not zero, so there will also be a zero frequency component.
  3. 1000 ms is not divisible by 3 ms. The discrete Fourier transform assumes that the entire signal repeats with period equal to the window length (1000 ms). This means that you have 332 intervals of 3 ms and 1 interval of 4 ms. As it is not periodic at 333 Hz, there will be a spread of frequencies.

You were using the correct values for n and d.
In general, I find it more helpful to plot the output than printing out the values.

import matplotlib.pyplot as plt
plt.plot(fs, amps)

see

pulse_freq_plot

Upvotes: 3

Related Questions