我使用这个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);
}
这里放置了一个链接:http://paulbourke.net/miscellaneous/dft/
第一个问题是为什么在应用直接变换(dir=1
)后,我们需要对值进行缩放?我读了一些关于DFT实现的想法,但没有找到有关此问题的任何信息。
我使用的输入是1024采样频率的cos。
#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;
}
}
为了绘图,我删除了之前问过的缩放操作,因为输出值变得非常小,无法绘制图形。
我得到了幅度和相位的图表:
![enter image description here](https://istack.dev59.com/NdDhU.webp)
![enter image description here](https://istack.dev59.com/YCmb2.webp)
如您所见,相位总是为0,幅度频谱被颠倒。为什么?
以下是更易读且不使用缩放操作的版本,其产生相同的结果:
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;
}
}
}
cos(i)
。这是我得到的 振幅 和 相位。振幅只有一点点不同,但相位出现了一些新的东西。这是在开头和结尾填充零时发生的。 - Long Smithsqrt(re^2 + im^2)
吗?请注意,输入应该在 x1 中有正弦波,在 y1 中填充零点 - 不要像你在问题代码中那样在开头和结尾填充零点。您可以使用已知的良好DFT或FFT实现(例如Octave(免费的MATLAB克隆版))检查结果。 - Paul R