I use this implementation of DFT:
/*
Direct fourier transform
*/
int DFT(int dir,int m,double *x1,double *y1)
{
long i,k;
double arg;
double cosarg,sinarg;
double *x2=NULL,*y2=NULL;
x2 = malloc(m*sizeof(double));
y2 = malloc(m*sizeof(double));
if (x2 == NULL || y2 == NULL)
return(FALSE);
for (i=0;i<m;i++) {
x2[i] = 0;
y2[i] = 0;
arg = - dir * 2.0 * 3.141592654 * (double)i / (double)m;
for (k=0;k<m;k++) {
cosarg = cos(k * arg);
sinarg = sin(k * arg);
x2[i] += (x1[k] * cosarg - y1[k] * sinarg);
y2[i] += (x1[k] * sinarg + y1[k] * cosarg);
}
}
/* Copy the data back */
if (dir == 1) {
for (i=0;i<m;i++) {
x1[i] = x2[i] / (double)m;
y1[i] = y2[i] / (double)m;
}
} else {
for (i=0;i<m;i++) {
x1[i] = x2[i];
y1[i] = y2[i];
}
}
free(x2);
free(y2);
return(TRUE);
}
Which is placed here http://paulbourke.net/miscellaneous/dft/
First question is why after applying direct transform(dir=1
) we should scale values? I read some ideas about DFT implementation and didn't find anything about it.
As input I use cos with 1024 sampling frequency
#define SAMPLES 2048
#define ZEROES_NUMBER 512
double step = PI_2/(SAMPLES-2*ZEROES_NUMBER);
for(int i=0; i<SAMPLES; i++)
{
/*
* Fill in the beginning and end with zeroes
*/
if(i<ZEROES_NUMBER || i > SAMPLES-ZEROES_NUMBER)
{
samplesReal[i] = 0;
samplesImag[i] = 0;
}
/*
* Generate one period cos with 1024 samples
*/
else
{
samplesReal[i] = cos(step*(double)(i-ZEROES_NUMBER));
samplesImag[i] = 0;
}
}
For plotting I removed scaling about which I asked above because output values become very small and it's impossible to plot graph.
And I got such graphs of amplitude and phase:
As you can see phase is always 0 and amplitude spectrum is reversed. Why?
Below is my more readable version without scaling which produces the same result:
void DFT_transform(double complex* samples, int num, double complex* res)
{
for(int k=0; k<num; k++)
{
res[k] = 0;
for(int n=0; n<num; n++)
{
double complex Wkn = cos(PI_2*(double)k*(double)n/(double)num) -
I*sin(PI_2*(double)k*(double)n/(double)num);
res[k] += samples[n]*Wkn;
}
}
}