I am testing my knowledge about Discrete Fourier Transforms.
What I am testing now is how to calculate the central frequency of a wave using DFT.
For that purpose I create a sinusoidal data using this code:
// create a 100 Hz wave with a sampling rate of 512 samples per second
var data : [Double] = []
for i in 0...511 {
let t = Double(i) * 100/256
let f = 10 * sin(2 * Double.pi * t)
data.append(f)
}
Then I do a DWT on data
and get two vectors, one containing the real part and one containing the imaginary part.
I understand that the inside each vector I will have this:
- data has 512 samples
- therefore, items from 0 to 256 will be the positive frequencies
- and items from 257 to 511, the negative frequencies
- I can discard the negative frequencies and keep the positive frequencies, from bin 0 to 255.
- Bin 0 is DC. I can discard it.
- Bin 255 will be 256Hz, because it is half of the sample rate.
To see if I get it right, I check the 256 bins and look for the highest magnitude. The bin with the highest magnitude will be K
on the following formula and I can find the signal frequency:
freq = (K + 1) * fps / N
K+1
because my first index is 0
and I have discarded DC from my array, and where N
is the number of samples.
The big problem is: how do I calculate the energy per bin?
E[i] = sqrt(realPart[i] * realPart[i] + imaginaryPart[i] * imaginaryPart[i])
????