Hello,
I'm trying to write the Cooley Turkey algorithm for an FFT. Now, The algorithm works well, but, only for 2 numbers - Nothing else. For example, I have used an online FFT calculated, entered the same data and got the same results. Here is the code for the algorithm:
#include <iostream>
#include <math.h>
#include <vector>
#include <complex>
using namespace std;
#define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr;
#define pi 3.14159
void ComplexFFT(vector<float> &realData, vector<float> &actualData, unsigned long sample_num, unsigned int sample_rate, int sign)
{
unsigned long n, mmax, m, j, istep, i;
double wtemp,wr,wpr,wpi,wi,theta,tempr,tempi;
// CHECK TO SEE IF VECTOR IS EMPTY;
actualData.resize(2*sample_num, 0);
for(n=0; (n < sample_rate); n++)
{
if(n < sample_num)
{
actualData[2*n] = realData[n];
}else{
actualData[2*n] = 0;
actualData[2*n+1] = 0;
}
}
// Binary Inversion
n = sample_rate << 1;
j = 0;
for(i=1; (i< n); i+=2)
{
if(j > i)
{
SWAP(actualData[j - 1], actualData[i - 1]);
SWAP(actualData[j], actualData[i]);
}
m = sample_rate;
while (m >= 2 && j > m) {
j -= m;
m >>= 1;
}
j += m;
}
mmax=2;
while(n > mmax) {
istep = mmax << 1;
theta = sign * (2*pi/mmax);
wtemp = sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi = sin(theta);
wr = 1.0;
wi = 0.0;
for(m=1; (m < mmax); m+=2) {
for(i=m; (i <= n); i += istep)
{
j = i + mmax;
tempr = wr*actualData[j-1]-wi*actualData[j];
tempi = wr*actualData[j]+wi*actualData[j-1];
actualData[j-1] = actualData[i-1] - tempr;
actualData[j] = actualData[i]-tempi;
actualData[i-1] += tempr;
actualData[i] += tempi;
}
wr = (wtemp=wr)*wpr-wi*wpi+wr;
wi = wi*wpr+wtemp*wpi+wi;
}
mmax = istep;
}
// determine if the fundamental frequency
int fundemental_frequency = 0;
for(i=2; (i <= sample_rate); i+=2)
{
if((pow(actualData[i], 2)+pow(actualData[i+1], 2)) > pow(actualData[fundemental_frequency], 2)+pow(actualData[fundemental_frequency+1], 2)) {
fundemental_frequency = i;
}
}
}
int main(int argc, char *argv[]) {
vector<float> numbers;
vector<float> realNumbers;
numbers.push_back(50);
numbers.push_back(10);
ComplexFFT(numbers, realNumbers, 2, 2, 0);
for(int i=0; (i < realNumbers.size()); i++)
{
cout << realNumbers[i] << ' ';
}
}
If I enter:
50, 10
Then the result would be:
60.00, 0.0
40.00, 0.0
And in the calculator, the exact same.
Where as if I entered:
50, 10
50, 10
The calculator returns results:
120.0, 0.0
0.0, 0.0
80.0, 0.0
0.0, 0.0
And my results return:
60, 60
24.6446, -45.3553
90, -10.0001
4.64479, 45.3555
Does anyone have any suggestions?
P.S. Does the algorithm only work for 2 digit values?
Thanks :)